import { cookies } from "next/headers";
import { prisma } from "../db";
import { emptyProfile, type ApplicantProfile } from "./schema";
import { computeProcess, type ProcessStep } from "./gates";

const COOKIE = "customerId";

export async function getOrCreateCustomerId(): Promise<string> {
  const jar = await cookies();
  const existing = jar.get(COOKIE)?.value;
  if (existing) {
    const found = await prisma.customer.findUnique({ where: { id: existing } });
    if (found) return found.id;
  }
  const created = await prisma.customer.create({ data: {} });
  jar.set(COOKIE, created.id, { path: "/", httpOnly: true, sameSite: "lax", maxAge: 60 * 60 * 24 * 365 });
  return created.id;
}

import { isPlausibleName } from "./usGeo";

export function syncCustomerFromProfile(profile: ApplicantProfile) {
  return {
    fullName: profile.name && isPlausibleName(profile.name) ? profile.name : undefined,
    phone: profile.phone ?? undefined,
    email: profile.email ?? undefined,
    state: profile.state ?? undefined,
    dateOfBirth: profile.date_of_birth ?? undefined,
    sex: profile.sex ?? undefined,
  };
}

export function profileIndex(profile: ApplicantProfile) {
  return {
    payloadJson: profile as object,
    loanBalance: profile.loan_balance ?? null,
    loanTermYears: profile.loan_term_years ?? null,
    coverageOnWhom: profile.coverage_on_whom ?? null,
    bmiComputed: profile.bmi_computed ?? null,
  };
}

export async function createMortgageCase() {
  const customerId = await getOrCreateCustomerId();
  const profile = emptyProfile();
  const process = computeProcess(profile);
  const icase = await prisma.insuranceCase.create({
    data: {
      customerId,
      vertical: "mortgage",
      processStep: process.step,
      status: "open",
      profile: { create: profileIndex(profile) },
      messages: {
        create: {
          role: "assistant",
          content:
            "Hi — I can help with U.S. mortgage protection (life insurance that can pay off or cover a home loan). What’s your name, and which U.S. state is the mortgage in?",
        },
      },
    },
    include: { profile: true, messages: true, customer: true },
  });
  return icase;
}

export async function loadCase(caseId: string) {
  return prisma.insuranceCase.findUnique({
    where: { id: caseId },
    include: { profile: true, messages: { orderBy: { createdAt: "asc" } }, customer: true },
  });
}

export function payloadFromRow(row: { payloadJson: unknown } | null): ApplicantProfile {
  if (!row?.payloadJson || typeof row.payloadJson !== "object") return emptyProfile();
  return { ...emptyProfile(), ...(row.payloadJson as ApplicantProfile) };
}

export function serializeCase(row: NonNullable<Awaited<ReturnType<typeof loadCase>>>) {
  const profile = payloadFromRow(row.profile);
  const process = computeProcess(profile, row.stopPath);
  return {
    caseId: row.id,
    customerId: row.customerId,
    vertical: row.vertical,
    status: row.status,
    stopPath: row.stopPath,
    processStep: (row.processStep as ProcessStep) ?? process.step,
    process,
    profile,
    customer: row.customer,
    messages: [...row.messages]
      .sort((a, b) => {
        const dt = a.createdAt.getTime() - b.createdAt.getTime();
        if (dt !== 0) return dt;
        if (a.role === b.role) return 0;
        return a.role === "user" ? -1 : 1;
      })
      .map((m) => ({
        id: m.id,
        role: m.role,
        content: m.content,
        citations: m.citationsJson,
        createdAt: m.createdAt,
      })),
  };
}
