const { PrismaClient } = require('@prisma/client')
const { randomBytes, scrypt } = require('crypto')
const { promisify } = require('util')

const prisma = new PrismaClient()
const scryptAsync = promisify(scrypt)

async function hashPassword(password) {
  const salt = randomBytes(16).toString('hex')
  const key = await scryptAsync(password.normalize('NFKC'), salt, 64, {
    N: 16384,
    r: 16,
    p: 1,
    maxmem: 128 * 16384 * 16 * 2,
  })
  return `${salt}:${key.toString('hex')}`
}

function getEnv(name) {
  return (process.env[name] || '').trim()
}

async function main() {
  const email = (getEnv('SUPERADMIN_EMAIL') || 'superadmin@innungsapp.de').toLowerCase()
  const name = getEnv('SUPERADMIN_NAME') || 'Super Admin'
  const userId = getEnv('SUPERADMIN_USER_ID') || 'superadmin-user-id'
  const accountId = getEnv('SUPERADMIN_ACCOUNT_ID') || 'superadmin-account-id'

  let password = getEnv('SUPERADMIN_PASSWORD')
  if (!password) {
    if (process.env.NODE_ENV === 'production') {
      throw new Error('SUPERADMIN_PASSWORD must be set in production.')
    }

    password = 'demo1234'
    console.warn('SUPERADMIN_PASSWORD not set. Using development fallback password.')
  }

  console.log(`Seeding superadmin user for ${email}...`)
  const hash = await hashPassword(password)

  const user = await prisma.user.upsert({
    where: { email },
    update: {
      name,
      emailVerified: true,
      role: 'admin',
    },
    create: {
      id: userId,
      name,
      email,
      emailVerified: true,
      role: 'admin',
    },
  })

  await prisma.account.upsert({
    where: { id: accountId },
    update: {
      accountId: user.id,
      providerId: 'credential',
      userId: user.id,
      password: hash,
    },
    create: {
      id: accountId,
      accountId: user.id,
      providerId: 'credential',
      userId: user.id,
      password: hash,
    },
  })

  console.log(`Done. Login: ${email} / ${password}`)
}

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