import assert from "node:assert/strict";
import test from "node:test";
import {
  payloadFromRow,
  profileIndex,
  serializeCase,
  syncCustomerFromProfile,
} from "@/lib/mortgage/caseService";
import { emptyProfile } from "@/lib/mortgage/schema";

test("syncCustomerFromProfile drops implausible names", () => {
  const sync = syncCustomerFromProfile({
    ...emptyProfile(),
    name: "only cigar smoker",
    phone: "5551234567",
    email: "a@b.com",
    state: "TX",
    date_of_birth: "01/01/1980",
    sex: "F",
  });
  assert.equal(sync.fullName, undefined);
  assert.equal(sync.phone, "5551234567");
  assert.equal(sync.state, "TX");
});

test("syncCustomerFromProfile keeps plausible name", () => {
  const sync = syncCustomerFromProfile({ ...emptyProfile(), name: "Ann Lee" });
  assert.equal(sync.fullName, "Ann Lee");
});

test("profileIndex maps numeric fields", () => {
  const idx = profileIndex({
    ...emptyProfile(),
    loan_balance: 100000,
    loan_term_years: 15,
    coverage_on_whom: "both",
    bmi_computed: 24.1,
  });
  assert.equal(idx.loanBalance, 100000);
  assert.equal(idx.loanTermYears, 15);
  assert.equal(idx.coverageOnWhom, "both");
  assert.equal(idx.bmiComputed, 24.1);
});

test("payloadFromRow empty and merge", () => {
  assert.equal(payloadFromRow(null).intent, null);
  assert.equal(payloadFromRow({ payloadJson: "x" }).intent, null);
  const p = payloadFromRow({ payloadJson: { name: "Ann", state: "FL" } });
  assert.equal(p.name, "Ann");
  assert.equal(p.state, "FL");
});

test("serializeCase maps messages and process", () => {
  const now = new Date();
  const out = serializeCase({
    id: "case-1",
    customerId: "cust-1",
    vertical: "mortgage",
    status: "open",
    stopPath: null,
    processStep: 0,
    profile: { payloadJson: { name: "Ann", phone: "1", state: "TX" } },
    messages: [
      { id: "m1", role: "assistant", content: "Hi", citationsJson: null, createdAt: now },
    ],
    customer: { id: "cust-1" },
  } as Parameters<typeof serializeCase>[0]);
  assert.equal(out.caseId, "case-1");
  assert.equal(out.messages[0].content, "Hi");
  assert.ok(out.process.step >= 1);
});
