import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@innungsapp/shared'
import { sendInviteEmail } from '@/lib/email'
import { auth } from '@/lib/auth'

export async function POST(req: NextRequest, { params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const body = await req.json().catch(() => null)

  if (!body?.name || !body?.email) {
    return NextResponse.json({ error: 'Name und E-Mail sind erforderlich.' }, { status: 400 })
  }

  const name: string = String(body.name).trim()
  const email: string = String(body.email).trim().toLowerCase()

  const org = await prisma.organization.findUnique({
    where: { slug },
    select: { id: true, name: true },
  })

  if (!org) {
    return NextResponse.json({ error: 'Organisation nicht gefunden.' }, { status: 404 })
  }

  // Check if email already registered in this org
  const existing = await prisma.member.findFirst({
    where: { orgId: org.id, email },
  })

  if (existing) {
    // Still send invite so user can log in — don't reveal whether they exist
    await sendInviteEmail({
      to: email,
      memberName: existing.name,
      orgName: org.name,
      apiUrl: process.env.BETTER_AUTH_URL!,
    })
    return NextResponse.json({ success: true })
  }

  // Create member record
  await prisma.member.create({
    data: {
      name,
      email,
      orgId: org.id,
      betrieb: '-',
      sparte: '-',
      ort: '-',
      status: 'aktiv',
    },
  })

  // Create auth user (may already exist)
  try {
    await auth.api.createUser({
      body: { name, email, role: 'user', password: undefined },
    })
  } catch {
    // User may already exist in auth system
  }

  await sendInviteEmail({
    to: email,
    memberName: name,
    orgName: org.name,
    apiUrl: process.env.BETTER_AUTH_URL!,
  })

  return NextResponse.json({ success: true })
}
