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

export type SourceField = {
  key: string;
  label: string;
  type: string;
  group: "core" | "custom";
};

const CORE_FIELDS: SourceField[] = [
  { key: "firstName", label: "First Name", type: "text", group: "core" },
  { key: "lastName", label: "Last Name", type: "text", group: "core" },
  { key: "name", label: "Full Name", type: "text", group: "core" },
  { key: "email", label: "Email", type: "email", group: "core" },
  { key: "cellPhone", label: "Cell Phone", type: "phone", group: "core" },
  { key: "homePhone", label: "Home Phone", type: "phone", group: "core" },
  { key: "address", label: "Street Address", type: "text", group: "core" },
  { key: "aptNumber", label: "Apt / Suite", type: "text", group: "core" },
  { key: "city", label: "City", type: "text", group: "core" },
  { key: "state", label: "State", type: "text", group: "core" },
  { key: "zip", label: "ZIP Code", type: "text", group: "core" },
  { key: "gender", label: "Gender", type: "text", group: "core" },
  { key: "dateOfBirth", label: "Date of Birth", type: "date", group: "core" },
  { key: "maritalStatus", label: "Marital Status", type: "text", group: "core" },
  { key: "visitType", label: "Visit Type", type: "text", group: "core" },
  { key: "prayerRequests", label: "Prayer Requests", type: "textarea", group: "core" },
  { key: "prayerForTeam", label: "Prayer For Team", type: "checkbox", group: "core" },
  { key: "prayerConfidential", label: "Prayer Confidential", type: "checkbox", group: "core" },
  { key: "messageTopics", label: "Message Topics", type: "multiselect", group: "core" },
  { key: "nextStep", label: "Next Step", type: "multiselect", group: "core" },
  { key: "howHeard", label: "How Heard", type: "multiselect", group: "core" },
  { key: "serviceAttended", label: "Service Attended", type: "text", group: "core" },
  { key: "attendanceDuration", label: "Attendance Duration", type: "text", group: "core" },
  { key: "campusPreference", label: "Campus Preference", type: "text", group: "core" },
  { key: "followUp", label: "Follow Up Notes", type: "textarea", group: "core" },
  { key: "notes", label: "Notes", type: "textarea", group: "core" },
  { key: "firstTimeGuestDate", label: "First Time Guest Date", type: "date", group: "core" },
  { key: "salvationDate", label: "Salvation Date", type: "date", group: "core" },
  { key: "collectionDate", label: "Collection Date", type: "date", group: "core" },
  { key: "submissionSource", label: "Submission Source", type: "text", group: "core" },
  { key: "createdAt", label: "Created At", type: "date", group: "core" },
];

export async function GET() {
  try {
    const session = await requireApiAuthWithOrg();

    const template = await prisma.formTemplate.findFirst({
      where: {
        organizationId: session.user.orgId!,
        isDefault: true,
        isActive: true,
      },
      include: {
        fields: {
          orderBy: { sortOrder: "asc" },
        },
      },
    });

    const coreKeys = new Set(CORE_FIELDS.map((f) => f.key));
    const customFields: SourceField[] = (template?.fields ?? [])
      .filter((f) => !coreKeys.has(f.key))
      .map((f) => ({
        key: `fieldData.${f.key}`,
        label: f.label,
        type: f.type,
        group: "custom" as const,
      }));

    return NextResponse.json({
      fields: [...CORE_FIELDS, ...customFields],
    });
  } catch (error) {
    return handleApiError(error);
  }
}
