import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { baseActiveContact, baseInactiveContact, baseNonPrimaryContact } from "../testing/fixtures";
import { run } from "./listContactPersonsByPartner";

describe("listContactPersonsByPartner", () => {
  it("returns all contact persons for a partner with multiple contacts", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveContact, baseInactiveContact, baseNonPrimaryContact]);

    const result = await run(mock.db, { partnerId: "partner-2" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([
        baseActiveContact,
        baseInactiveContact,
        baseNonPrimaryContact,
      ]);
      expect(result.value.hasNextPage).toBe(false);
    }
  });

  it("returns empty array when partner has no contact persons", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { partnerId: "partner-2" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([]);
      expect(result.value.hasNextPage).toBe(false);
    }
  });

  it("includes both ACTIVE and INACTIVE contact persons", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveContact, baseInactiveContact]);

    const result = await run(mock.db, { partnerId: "partner-2" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      const statuses = result.value.items.map((c) => c.status);
      expect(statuses).toContain("ACTIVE");
      expect(statuses).toContain("INACTIVE");
    }
  });

  it("includes both primary and non-primary contact persons", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveContact, baseNonPrimaryContact]);

    const result = await run(mock.db, { partnerId: "partner-2" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      const primaries = result.value.items.map((c) => c.isPrimary);
      expect(primaries).toContain(true);
      expect(primaries).toContain(false);
    }
  });

  it("returns empty array for an INDIVIDUAL-type partner", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { partnerId: "partner-4" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([]);
    }
  });
});
