import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { baseTaxIdIdentification, baseVatIdentification } from "../testing/fixtures";
import { run } from "./listPartnerIdentificationsByPartner";

describe("listPartnerIdentificationsByPartner", () => {
  it("returns all identification records for a partner with multiple identifications", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseTaxIdIdentification, baseVatIdentification]);

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

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

  it("returns only TAX_ID records when type filter is provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseTaxIdIdentification]);

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

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

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

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

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

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

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

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

  it("includes identifications regardless of validity period", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseTaxIdIdentification, baseVatIdentification]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      const hasNoExpiry = result.value.items.some((i) => i.validTo === null);
      const hasExpiry = result.value.items.some((i) => i.validTo !== null);
      expect(hasNoExpiry).toBe(true);
      expect(hasExpiry).toBe(true);
    }
  });
});
