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

export async function GET(request: NextRequest) {
  try {
    const session = await requireApiAuthWithOrg();
    const orgId = session.user.orgId!;

    const { searchParams } = new URL(request.url);
    const page = Math.max(1, parseInt(searchParams.get("page") ?? "1", 10));
    const limit = Math.min(100, Math.max(1, parseInt(searchParams.get("limit") ?? "20", 10)));
    const search = searchParams.get("search")?.trim() || undefined;
    const sortBy = searchParams.get("sortBy") ?? "createdAt";
    const sortOrder = searchParams.get("sortOrder") ?? "desc";

    const validSortFields = ["createdAt", "updatedAt", "firstName", "lastName", "email"];
    const orderByField = validSortFields.includes(sortBy) ? sortBy : "createdAt";
    const order = sortOrder === "asc" ? "asc" : "desc";

    const where: Record<string, unknown> = {
      organizationId: orgId,
      mergedIntoId: null,
    };

    if (search) {
      where.OR = [
        { firstName: { contains: search, mode: "insensitive" } },
        { lastName: { contains: search, mode: "insensitive" } },
        { email: { contains: search, mode: "insensitive" } },
      ];
    }

    const [people, total] = await Promise.all([
      prisma.person.findMany({
        where,
        orderBy: { [orderByField]: order },
        skip: (page - 1) * limit,
        take: limit,
        include: { _count: { select: { cards: true } } },
      }),
      prisma.person.count({ where }),
    ]);

    return NextResponse.json({ people, total, page, limit });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function POST(request: NextRequest) {
  try {
    const session = await requireApiAuthWithOrg();
    const orgId = session.user.orgId!;

    const body = await request.json().catch(() => ({}));
    const { firstName, lastName, email, cellPhone, fieldData } = body;

    if (!firstName || !lastName) {
      return NextResponse.json(
        { error: "firstName and lastName are required" },
        { status: 400 }
      );
    }

    const person = await prisma.person.create({
      data: {
        organizationId: orgId,
        firstName: String(firstName).trim(),
        lastName: String(lastName).trim(),
        email: email ? String(email).trim().toLowerCase() : null,
        cellPhone: cellPhone ? String(cellPhone).trim() : null,
        fieldData: fieldData ?? null,
      },
    });

    return NextResponse.json(person, { status: 201 });
  } catch (error) {
    return handleApiError(error);
  }
}
