import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@innungsapp/shared'

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

  if (!body?.email) {
    return NextResponse.json({ error: 'E-Mail ist erforderlich.' }, { status: 400 })
  }

  const email: string = String(body.email).trim().toLowerCase()
  const name: string = String(body.name ?? '').trim() || email.split('@')[0]

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

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

  // Look up the auth user that better-auth just created
  const authUser = await prisma.user.findUnique({
    where: { email },
    select: { id: true },
  })

  if (!authUser) {
    return NextResponse.json({ error: 'Benutzer nicht gefunden. Bitte zuerst registrieren.' }, { status: 400 })
  }

  // Idempotent: skip if member already exists (linked to this user)
  const existingMember = await prisma.member.findFirst({
    where: { orgId: org.id, userId: authUser.id },
  })

  if (!existingMember) {
    // Member may exist without userId (created by admin before user registered)
    const unlinkedMember = await prisma.member.findFirst({
      where: { orgId: org.id, email, userId: null },
    })

    if (unlinkedMember) {
      await prisma.member.update({
        where: { id: unlinkedMember.id },
        data: { userId: authUser.id },
      })
    } else {
      await prisma.member.create({
        data: {
          name,
          email,
          orgId: org.id,
          userId: authUser.id,
          betrieb: '-',
          sparte: '-',
          ort: '-',
          status: 'aktiv',
        },
      })
    }
  }

  // Idempotent: skip if role already exists
  const existingRole = await prisma.userRole.findFirst({
    where: { userId: authUser.id, orgId: org.id },
  })

  if (!existingRole) {
    await prisma.userRole.create({
      data: {
        userId: authUser.id,
        orgId: org.id,
        role: 'member',
      },
    })
  }

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