import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } 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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseActiveContact, baseInactiveContact, baseNonPrimaryContact]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseActiveContact, baseInactiveContact]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseActiveContact, baseNonPrimaryContact]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([]);

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

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