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 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,
    }) as Buffer
    return `${salt}:${key.toString('hex')}`
}

function getEnv(name: string): string {
    return (process.env[name] ?? '').trim()
}

async function main() {
    const email = getEnv('SUPERADMIN_EMAIL').toLowerCase() || 'superadmin@innungsapp.de'
    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 superAdminUser = 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: superAdminUser.id,
            userId: superAdminUser.id,
            providerId: 'credential',
            password: hash,
        },
        create: {
            id: accountId,
            accountId: superAdminUser.id,
            providerId: 'credential',
            userId: superAdminUser.id,
            password: hash,
        },
    })

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

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