import { describe, expect, test } from "bun:test";
import {
  isSameDayAppointment,
  isSameServiceSameProviderSlot,
  shouldEscalateForLanguage,
  verifyPatientIdentity,
} from "./scheduling-policy.ts";

describe("scheduling policy", () => {
  test("requires single candidate, phone, legal name, and DOB match", () => {
    const result = verifyPatientIdentity({
      callerNumber: "+1 (972) 555-0100",
      statedLegalName: "Jane Smith",
      statedDob: "1980-01-02",
      candidates: [
        {
          patientId: "p1",
          legalName: "Jane Smith",
          dob: "1980-01-02",
          phones: ["9725550100"],
        },
      ],
    });

    expect(result.ok).toBe(true);
    if (result.ok) expect(result.patient.patientId).toBe("p1");
  });

  test("uses caller phone to disambiguate multiple candidates", () => {
    const result = verifyPatientIdentity({
      callerNumber: "9725550100",
      statedLegalName: "Jane Smith",
      statedDob: "1980-01-02",
      candidates: [
        { patientId: "p1", legalName: "Jane Smith", dob: "1980-01-02", phones: ["2145550100"] },
        { patientId: "p2", legalName: "Jane Smith", dob: "1980-01-02", phones: ["9725550100"] },
      ],
    });

    expect(result.ok).toBe(true);
    if (result.ok) expect(result.patient.patientId).toBe("p2");
  });

  test("escalates multiple candidates when caller phone is not unique", () => {
    const result = verifyPatientIdentity({
      callerNumber: "9725550100",
      statedLegalName: "Jane Smith",
      statedDob: "1980-01-02",
      candidates: [
        { patientId: "p1", legalName: "Jane Smith", dob: "1980-01-02", phones: ["9725550100"] },
        { patientId: "p2", legalName: "Jane Smith", dob: "1980-01-02", phones: ["9725550100"] },
      ],
    });

    expect(result).toEqual({ ok: false, reason: "multiple_candidates" });
  });

  test("allows only same-provider same-service slots", () => {
    expect(
      isSameServiceSameProviderSlot(
        {
          appointmentId: "a1",
          patientId: "p1",
          providerId: "prov1",
          serviceCode: "therapy",
          startsAt: "2026-06-02T14:00:00.000Z",
        },
        {
          providerId: "prov1",
          serviceCode: "therapy",
          startsAt: "2026-06-03T14:00:00.000Z",
          durationMinutes: 60,
        },
      ),
    ).toBe(true);
  });

  test("detects same-day and escalation language", () => {
    expect(
      isSameDayAppointment(
        {
          appointmentId: "a1",
          patientId: "p1",
          providerId: "prov1",
          serviceCode: "therapy",
          startsAt: "2026-06-01T14:00:00.000Z",
        },
        new Date("2026-06-01T10:00:00.000Z"),
      ),
    ).toBe(true);
    expect(shouldEscalateForLanguage("I have chest pain and need to reschedule")).toBe(true);
  });
});
