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

async function main() {
    console.log('Seeding superadmin...')
    const hash = await hashPassword('demo1234')
    console.log('Hash generated.')

    const superAdminUser = await prisma.user.upsert({
        where: { email: 'superadmin@innungsapp.de' },
        update: {},
        create: {
            id: 'superadmin-user-id',
            name: 'Super Admin',
            email: 'superadmin@innungsapp.de',
            emailVerified: true,
        },
    })

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

    console.log('Done! Login: superadmin@innungsapp.de / demo1234')
}

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