import { PrismaClient } from '../generated'
import bcrypt from 'bcryptjs'
import { ensureDatabaseUrl } from '../src/runtime-config'

ensureDatabaseUrl()

const prisma = new PrismaClient()

async function main() {
  const email = process.env.ADMIN_SEED_EMAIL ?? 'admin@rentaldrivego.ma'
  const password = process.env.ADMIN_SEED_PASSWORD ?? 'changeme123'
  const firstName = process.env.ADMIN_SEED_FIRST_NAME ?? 'Super'
  const lastName = process.env.ADMIN_SEED_LAST_NAME ?? 'Admin'

  const existing = await prisma.adminUser.findUnique({ where: { email } })
  if (existing) {
    console.log(`Super admin already exists: ${email}`)
    return
  }

  const passwordHash = await bcrypt.hash(password, 12)

  const admin = await prisma.adminUser.create({
    data: {
      email,
      firstName,
      lastName,
      passwordHash,
      role: 'SUPER_ADMIN',
      isActive: true,
    },
  })

  console.log(`Created SUPER_ADMIN: ${admin.email} (id: ${admin.id})`)
  console.log('Login with the password you set in ADMIN_SEED_PASSWORD')
}

main()
  .catch((err) => {
    console.error(err)
    process.exit(1)
  })
  .finally(() => prisma.$disconnect())
