/**
 * Seed script for Actuate CMS.
 *
 * Reads credentials from environment variables (never hardcoded):
 *   CMS_ADMIN_EMAIL, CMS_ADMIN_PASSWORD, CMS_ADMIN_NAME
 *
 * Usage:
 *   cd packages/cms-core
 *   pnpm tsx prisma/seed.ts
 *
 * Requires DATABASE_URL + CMS_ADMIN_* vars in environment or .env file.
 */

import 'dotenv/config'
import pg from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '../generated/client.js'

async function main() {
  const email = process.env.CMS_ADMIN_EMAIL
  const password = process.env.CMS_ADMIN_PASSWORD
  const name = process.env.CMS_ADMIN_NAME ?? 'Admin'

  if (!email || !password) {
    console.error('Set CMS_ADMIN_EMAIL and CMS_ADMIN_PASSWORD in your .env file')
    process.exit(1)
  }

  const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
  const adapter = new PrismaPg(pool)
  const prisma = new PrismaClient({ adapter })

  try {
    const existingCount = await prisma.user.count()
    if (existingCount > 0) {
      console.log(`Skipping seed — ${existingCount} user(s) already exist.`)
      return
    }

    const salt = crypto.getRandomValues(new Uint8Array(16))
    const key = await crypto.subtle.importKey(
      'raw',
      new TextEncoder().encode(password),
      'PBKDF2',
      false,
      ['deriveBits'],
    )
    const derived = await crypto.subtle.deriveBits(
      { name: 'PBKDF2', salt, iterations: 100_000, hash: 'SHA-256' },
      key,
      256,
    )
    const saltHex = Buffer.from(salt).toString('hex')
    const hashHex = Buffer.from(derived).toString('hex')
    const passwordHash = `pbkdf2:100000:${saltHex}:${hashHex}`

    const user = await prisma.user.create({
      data: {
        email: email.toLowerCase().trim(),
        name,
        passwordHash,
        role: 'ADMIN',
        isActive: true,
        isApproved: true,
        emailVerified: true,
      },
    })

    console.log(`Seeded admin user:`)
    console.log(`  Email: ${email}`)
    console.log(`  Role:  ADMIN`)
    console.log(`  ID:    ${user.id}`)
  } finally {
    await prisma.$disconnect()
    await pool.end()
  }
}

main().catch((err) => {
  console.error('Seed failed:', err)
  process.exit(1)
})
