import { NextRequest, NextResponse } from "next/server"
import { hash } from "bcryptjs"
import prisma from "@/lib/prisma"

export async function POST(request: NextRequest) {
  try {
    if (!prisma) return NextResponse.json({ error: "DB not configured" }, { status: 503 })

    const { email, password, name, charityName } = await request.json()

    if (!email || !password || !charityName) {
      return NextResponse.json({ error: "Email, password and charity name are required" }, { status: 400 })
    }
    if (password.length < 8) {
      return NextResponse.json({ error: "Password must be at least 8 characters" }, { status: 400 })
    }

    const cleanEmail = email.toLowerCase().trim()

    // Check if email exists
    const existing = await prisma.user.findUnique({ where: { email: cleanEmail } })
    if (existing) {
      return NextResponse.json({ error: "An account with this email already exists" }, { status: 409 })
    }

    // Create org + user in transaction
    const slug = charityName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "").slice(0, 50)
    const hashedPassword = await hash(password, 12)

    const result = await prisma.$transaction(async (tx) => {
      const org = await tx.organization.create({
        data: {
          name: charityName.trim(),
          slug: slug + "-" + Date.now().toString(36),
          country: "GB",
          refPrefix: slug.substring(0, 4).toUpperCase() || "PNPL",
        },
      })

      const user = await tx.user.create({
        data: {
          email: cleanEmail,
          name: name?.trim() || null,
          hashedPassword,
          role: "org_admin",
          organizationId: org.id,
        },
      })

      return { userId: user.id, orgId: org.id, orgName: org.name }
    })

    return NextResponse.json(result, { status: 201 })
  } catch (error) {
    console.error("Signup error:", error)
    return NextResponse.json({ error: "Failed to create account" }, { status: 500 })
  }
}
