// Maak een admin-user aan of upgrade een bestaande user naar ADMIN-rol.
//
// Gebruik:
//   npx tsx scripts/create-admin.ts <username> <password>

import { PrismaClient } from '@prisma/client'
import { Pool } from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'
import * as bcrypt from 'bcryptjs'
import * as dotenv from 'dotenv'
import * as path from 'path'

const root = path.resolve(__dirname, '..')
dotenv.config({ path: path.join(root, '.env.local'), override: true })
dotenv.config({ path: path.join(root, '.env') })

const [username, password] = process.argv.slice(2)

if (!username || !password) {
  console.error('Usage: npx tsx scripts/create-admin.ts <username> <password>')
  process.exit(1)
}

const url = process.env.DIRECT_URL || process.env.DATABASE_URL
if (!url) {
  console.error('Fout: DATABASE_URL is niet ingesteld.')
  process.exit(1)
}

const pool = new Pool({ connectionString: url })
const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })

async function main() {
  let user = await prisma.user.findUnique({ where: { username } })

  if (!user) {
    const password_hash = await bcrypt.hash(password, 12)
    user = await prisma.user.create({ data: { username, password_hash } })
    console.log(`Gebruiker '${username}' aangemaakt.`)
  } else {
    console.log(`Gebruiker '${username}' gevonden — rol wordt geüpgraded.`)
  }

  await prisma.userRole.upsert({
    where: { user_id_role: { user_id: user.id, role: 'ADMIN' } },
    create: { user_id: user.id, role: 'ADMIN' },
    update: {},
  })
  console.log(`Admin-rol toegewezen aan '${username}'.`)
}

main()
  .catch((err) => {
    console.error('Fout:', err.message)
    process.exit(1)
  })
  .finally(() => prisma.$disconnect())
