import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireApiAuthWithOrg, handleApiError } from "@/lib/api-auth";

type Ctx = { params: Promise<{ id: string }> };

export async function GET(_request: NextRequest, ctx: Ctx) {
  try {
    const session = await requireApiAuthWithOrg();
    const { id } = await ctx.params;

    const person = await prisma.person.findUnique({
      where: { id },
      include: {
        cards: {
          take: 20,
          orderBy: { createdAt: "desc" },
          select: {
            id: true,
            name: true,
            ocrStatus: true,
            reviewStatus: true,
            createdAt: true,
          },
        },
        _count: { select: { cards: true } },
      },
    });

    if (!person || person.organizationId !== session.user.orgId) {
      return NextResponse.json({ error: "Person not found" }, { status: 404 });
    }

    return NextResponse.json(person);
  } catch (error) {
    return handleApiError(error);
  }
}

export async function PUT(request: NextRequest, ctx: Ctx) {
  try {
    const session = await requireApiAuthWithOrg();
    const { id } = await ctx.params;

    const existing = await prisma.person.findUnique({ where: { id } });
    if (!existing || existing.organizationId !== session.user.orgId) {
      return NextResponse.json({ error: "Person not found" }, { status: 404 });
    }

    const body = await request.json().catch(() => ({}));
    const data: Record<string, unknown> = {};

    if (body.firstName != null) data.firstName = String(body.firstName).trim();
    if (body.lastName != null) data.lastName = String(body.lastName).trim();
    if (body.email !== undefined) {
      data.email = body.email ? String(body.email).trim().toLowerCase() : null;
    }
    if (body.cellPhone !== undefined) {
      data.cellPhone = body.cellPhone ? String(body.cellPhone).trim() : null;
    }
    if (body.fieldData != null) {
      data.fieldData = { ...((existing.fieldData as object) ?? {}), ...body.fieldData };
    }

    const updated = await prisma.person.update({ where: { id }, data });
    return NextResponse.json(updated);
  } catch (error) {
    return handleApiError(error);
  }
}

export async function DELETE(_request: NextRequest, ctx: Ctx) {
  try {
    const session = await requireApiAuthWithOrg();
    const { id } = await ctx.params;

    const existing = await prisma.person.findUnique({ where: { id } });
    if (!existing || existing.organizationId !== session.user.orgId) {
      return NextResponse.json({ error: "Person not found" }, { status: 404 });
    }

    await prisma.responseCard.updateMany({
      where: { personId: id },
      data: { personId: null },
    });

    await prisma.person.delete({ where: { id } });

    return NextResponse.json({ success: true });
  } catch (error) {
    return handleApiError(error);
  }
}
