/**
 * Sets admin@demo.de password using better-auth's exact hash format:
 * `${hex-salt}:${hex-scrypt-key}` (from better-auth/dist/crypto/password.mjs)
 *
 * Run: pnpm --filter @innungsapp/shared prisma:seed-admin
 */
import { PrismaClient } from '@prisma/client'
import { scrypt, randomBytes } from 'crypto'
import { promisify } from 'util'

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

async function hashPassword(password: string): Promise<string> {
  const saltBytes = randomBytes(16)
  const salt = saltBytes.toString('hex') // better-auth uses hex-encoded salt
  const key = await scryptAsync(
    password.normalize('NFKC'),
    salt,
    64, // dkLen
    { N: 16384, r: 16, p: 1, maxmem: 128 * 16384 * 16 * 2 }
  ) as Buffer
  return `${salt}:${key.toString('hex')}`
}

async function main() {
  console.log('Generating better-auth compatible hash...')
  const hash = await hashPassword('demo1234')

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

  console.log('Done! Login: admin@demo.de / demo1234')
}

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