/**
 * Creates User accounts + passwords for the 3 demo members so they can log in.
 * Run: pnpm --filter @innungsapp/shared prisma:seed-demo-members
 */
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')}`
}

const DEMO_MEMBERS = [
  { id: 'demo-maria-user-id', accountId: 'demo-maria-account-id', name: 'Maria Schmidt', email: 'schmidt@schmidt-elektrik.de', password: 'demo1234' },
  { id: 'demo-klaus-user-id', accountId: 'demo-klaus-account-id', name: 'Klaus Müller', email: 'mueller@elektro-mueller.de', password: 'demo1234' },
  { id: 'demo-thomas-user-id', accountId: 'demo-thomas-account-id', name: 'Thomas Weber', email: 'weber@weber-elektro.de', password: 'demo1234' },
]

async function main() {
  const org = await prisma.organization.findFirst({ where: { slug: 'innung-elektro-stuttgart' } })
  if (!org) throw new Error('Org not found — run pnpm db:seed first')

  for (const m of DEMO_MEMBERS) {
    const hash = await hashPassword(m.password)

    // Create User
    const user = await prisma.user.upsert({
      where: { email: m.email },
      update: {},
      create: { id: m.id, name: m.name, email: m.email, emailVerified: true },
    })

    // Create password account
    await prisma.account.upsert({
      where: { id: m.accountId },
      update: { password: hash },
      create: {
        id: m.accountId,
        accountId: user.id,
        providerId: 'credential',
        userId: user.id,
        password: hash,
      },
    })

    // Create org role
    await prisma.userRole.upsert({
      where: { orgId_userId: { orgId: org.id, userId: user.id } },
      update: {},
      create: { orgId: org.id, userId: user.id, role: 'member' },
    })

    // Link first unlinked member record to user (skip if already linked)
    const existingMember = await prisma.member.findFirst({
      where: { email: m.email, orgId: org.id },
      orderBy: { createdAt: 'asc' },
    })
    if (existingMember && existingMember.userId === null) {
      await prisma.member.update({
        where: { id: existingMember.id },
        data: { userId: user.id },
      })
    }

    console.log(`✓ ${m.name} — ${m.email} / ${m.password}`)
  }

  console.log('\nAlle Demo-Mitglieder können sich jetzt einloggen!')
}

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