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')}`
}

async function main() {
  const email = 'superadmin@innungsapp.de'
  const password = 'demo1234'
  const userId = 'superadmin-user-id'
  const accountId = 'superadmin-account-id'

  console.log('Seeding superadmin...')
  const hash = await hashPassword(password)

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

  await prisma.account.upsert({
    where: { id: accountId },
    update: { 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()
  })
