import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { formTemplateId, organizationId, firstName, lastName, fieldData } =
      body as {
        formTemplateId?: string;
        organizationId?: string;
        firstName?: string;
        lastName?: string;
        fieldData?: Record<string, string>;
      };

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

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

    const template = await prisma.formTemplate.findUnique({
      where: { id: formTemplateId },
    });

    if (
      !template ||
      !template.isActive ||
      template.organizationId !== organizationId
    ) {
      return NextResponse.json(
        { error: "Form template not found or inactive" },
        { status: 404 }
      );
    }

    const trimmedFirst = firstName.trim();
    const trimmedLast = lastName.trim();

    const card = await prisma.responseCard.create({
      data: {
        firstName: trimmedFirst,
        lastName: trimmedLast,
        name: `${trimmedFirst} ${trimmedLast}`,
        email: fieldData?.email || null,
        cellPhone: fieldData?.cellPhone || fieldData?.phone || null,
        fieldData: fieldData ?? {},
        formTemplateId,
        organizationId,
        ocrStatus: "complete",
        reviewStatus: "unreviewed",
        submissionSource: "survey",
      },
    });

    // TODO: Rate limiting — add IP-based or fingerprint-based rate limiting

    return NextResponse.json({ success: true, cardId: card.id });
  } catch (error) {
    console.error("[Survey Submit Error]", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
