"use server";

import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";

function str(formData: FormData, key: string): string | null {
  const v = formData.get(key);
  if (typeof v !== "string" || v.trim() === "") return null;
  return v.trim();
}

async function findRoutedBroker(area: string | null, type: string | null) {
  if (!area) return null;

  const candidates = await prisma.brokerCoverage.findMany({
    where: { area: { equals: area } },
  });
  if (candidates.length === 0) return null;

  const typeMatch = type ? candidates.find((c) => c.propertyType === type) : undefined;
  const anyTypeMatch = candidates.find((c) => c.propertyType === null);
  const chosen = typeMatch ?? anyTypeMatch ?? candidates[0];

  return chosen.brokerId;
}

export async function submitEnquiry(formData: FormData) {
  const area = str(formData, "areaOfInterest");
  const type = str(formData, "propertyTypeInterest");
  const propertyIdStr = str(formData, "propertyId");

  const routedBrokerId = await findRoutedBroker(area, type);

  await prisma.enquiry.create({
    data: {
      firstName: str(formData, "firstName") ?? "",
      lastName: str(formData, "lastName") ?? "",
      email: str(formData, "email") ?? "",
      phone: str(formData, "phone") ?? "",
      company: str(formData, "company"),
      propertyTypeInterest: type as "OFFICE" | "INDUSTRIAL" | "RETAIL" | null,
      listingTypeInterest: str(formData, "listingTypeInterest") as "TO_LET" | "FOR_SALE" | "SERVICED" | null,
      areaOfInterest: area,
      moveInTimeline: str(formData, "moveInTimeline"),
      message: str(formData, "message"),
      routedBrokerId,
      propertyId: propertyIdStr ? Number(propertyIdStr) : null,
    },
  });

  redirect("/contact?submitted=1");
}
