/**
 * DEV-ONLY: Sets a password for the demo admin user via better-auth.
 * Call once after seeding: GET http://localhost:3010/api/setup
 * Remove this file before going to production.
 */
import { NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@innungsapp/shared'

export async function GET() {
  if (process.env.NODE_ENV === 'production') {
    return NextResponse.json({ error: 'Not available in production' }, { status: 403 })
  }

  // Delete the pre-seeded user so better-auth can create it fresh with a hashed password
  await prisma.account.deleteMany({ where: { userId: 'demo-admin-user-id' } })
  await prisma.member.deleteMany({ where: { userId: 'demo-admin-user-id' } })
  await prisma.userRole.deleteMany({ where: { userId: 'demo-admin-user-id' } })
  await prisma.user.deleteMany({ where: { id: 'demo-admin-user-id' } })

  // Re-create via better-auth so the password is properly hashed
  const result = await auth.api.signUpEmail({
    body: { email: 'admin@demo.de', password: 'demo1234', name: 'Demo Admin' },
  })

  if (!result?.user) {
    return NextResponse.json({ error: 'signUp failed', result }, { status: 500 })
  }

  const newUserId = result.user.id

  // Restore org membership for the new user ID
  const org = await prisma.organization.findFirst({ where: { slug: 'innung-elektro-stuttgart' } })
  if (org) {
    await prisma.userRole.upsert({
      where: { orgId_userId: { orgId: org.id, userId: newUserId } },
      update: {},
      create: { orgId: org.id, userId: newUserId, role: 'admin' },
    })
    await prisma.member.upsert({
      where: { userId: newUserId },
      update: {},
      create: {
        orgId: org.id,
        userId: newUserId,
        name: 'Demo Admin',
        betrieb: 'Innungsgeschäftsstelle',
        sparte: 'Elektrotechnik',
        ort: 'Stuttgart',
        email: 'admin@demo.de',
        status: 'aktiv',
      },
    })
  }

  return NextResponse.json({
    ok: true,
    message: 'Setup complete. Login: admin@demo.de / demo1234',
  })
}
