import 'dotenv/config'
import { getDb } from './index.js'
import { logger } from '../lib/logger.js'
import bcrypt from 'bcryptjs'

async function seed() {
  const db = getDb()

  try {
    logger.info('Seeding database...')

    // Seed default admin user
    const passwordHash = await bcrypt.hash('admin123', 10)
    await db.query(
      `INSERT INTO users (email, name, password_hash, role) 
       VALUES ($1, $2, $3, $4) 
       ON CONFLICT (email) DO NOTHING`,
      ['admin@sankofa.nexus', 'Admin User', passwordHash, 'ADMIN']
    )
    logger.info('✓ Seeded admin user (admin@sankofa.nexus / admin123)')

    // Seed sample regions
    const regions = [
      { name: 'US East', code: 'us-east-1', country: 'United States', latitude: 39.8283, longitude: -98.5795 },
      { name: 'US West', code: 'us-west-1', country: 'United States', latitude: 37.7749, longitude: -122.4194 },
      { name: 'EU Central', code: 'eu-central-1', country: 'Germany', latitude: 52.5200, longitude: 13.4050 },
      { name: 'APAC Singapore', code: 'ap-southeast-1', country: 'Singapore', latitude: 1.3521, longitude: 103.8198 },
    ]

    for (const region of regions) {
      const result = await db.query(
        `INSERT INTO regions (name, code, country, latitude, longitude)
         VALUES ($1, $2, $3, $4, $5)
         ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name
         RETURNING id`,
        [region.name, region.code, region.country, region.latitude, region.longitude]
      )
      const regionId = result.rows[0].id

      // Seed sample sites for each region
      await db.query(
        `INSERT INTO sites (name, region, region_id, status)
         VALUES ($1, $2, $3, $4)
         ON CONFLICT DO NOTHING`,
        [`${region.name} Primary Site`, region.code, regionId, 'ACTIVE']
      )
    }
    logger.info(`✓ Seeded ${regions.length} regions with sites`)

    // Seed WAF pillars
    const pillars = [
      { code: 'SECURITY', name: 'Security' },
      { code: 'RELIABILITY', name: 'Reliability' },
      { code: 'COST_OPTIMIZATION', name: 'Cost Optimization' },
      { code: 'PERFORMANCE_EFFICIENCY', name: 'Performance Efficiency' },
      { code: 'OPERATIONAL_EXCELLENCE', name: 'Operational Excellence' },
      { code: 'SUSTAINABILITY', name: 'Sustainability' },
    ]

    for (const pillar of pillars) {
      await db.query(
        `INSERT INTO pillars (code, name)
         VALUES ($1, $2)
         ON CONFLICT (code) DO NOTHING`,
        [pillar.code, pillar.name]
      )
    }
    logger.info(`✓ Seeded ${pillars.length} WAF pillars`)

    logger.info('✓ Database seeding completed!')
  } catch (error) {
    logger.error('Seeding error', { error })
    throw error
  } finally {
    await db.end()
  }
}

seed().catch((error) => {
  logger.error('Failed to seed database', { error })
  process.exit(1)
})

