import { expect, test } from "@playwright/test";
import { createCase, openCaseOnStep, sendChat, sendMany, STEP_SCRIPT } from "./helpers";

test("step 5 primary: asks annual income after diseases", async ({ request, page }) => {
  const created = await createCase(request);
  const c = await sendMany(request, created.caseId, [
    STEP_SCRIPT.name,
    STEP_SCRIPT.state,
    STEP_SCRIPT.intent,
    STEP_SCRIPT.age,
    STEP_SCRIPT.loan,
    STEP_SCRIPT.build,
    STEP_SCRIPT.diseases,
  ]);
  expect(c.process.step).toBe(5);
  expect(c.process.missingRequired).toEqual(expect.arrayContaining(["annual_income"]));
  const last = c.messages[c.messages.length - 1];
  expect(last.content).toMatch(/annual|income/i);

  await openCaseOnStep(page, c.caseId);
  await expect(page.getByTestId("process-current")).toHaveText("Spouse / income");
  await expect(page.getByTestId("process-exit-gate")).toContainText("Income");
  await expect(page.getByText("R annual_income")).toBeVisible();

  const paid = await sendChat(request, c.caseId, STEP_SCRIPT.income);
  expect(paid.profile.annual_income).toBe(85000);
  expect(paid.process.step).toBeGreaterThanOrEqual(6);
});

test("step 5 co-borrower: spouse age, spouse income, then applicant income", async ({
  request,
  page,
}) => {
  const created = await createCase(request);
  const c = await sendMany(request, created.caseId, [
    "My name is Alex Rivera",
    "Ohio",
    "mortgage protection for both of us on the loan",
    STEP_SCRIPT.age,
    "loan balance 250k usd, 25 years left",
    STEP_SCRIPT.build,
    STEP_SCRIPT.diseases,
  ]);
  expect(c.profile.co_borrower_flag).toBe(true);
  expect(c.process.step).toBe(5);
  expect(c.process.missingRequired).toEqual(
    expect.arrayContaining(["spouse_age_sex", "spouse_annual_income", "annual_income"])
  );

  await openCaseOnStep(page, c.caseId);
  await expect(page.getByTestId("process-current")).toHaveText("Spouse / income");
  await expect(page.getByText("R spouse_annual_income")).toBeVisible();

  const spouse = await sendChat(request, c.caseId, "spouse is 36");
  expect(spouse.profile.spouse_age_sex).toBeTruthy();
  expect(spouse.process.step).toBe(5);

  const spInc = await sendChat(request, c.caseId, STEP_SCRIPT.spouseIncome);
  expect(spInc.profile.spouse_annual_income).toBe(40000);
  expect(spInc.process.step).toBe(5);

  const mine = await sendChat(request, c.caseId, STEP_SCRIPT.income);
  expect(mine.profile.annual_income).toBe(85000);

  const bene = await sendChat(request, c.caseId, "beneficiary is my spouse");
  expect(bene.profile.beneficiary_relationship).toBe("spouse");
  expect(bene.process.step).toBeGreaterThanOrEqual(6);
});
