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

describe("listPartnerAddressesByPartner", () => {
  it("returns all addresses for a partner with multiple addresses", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseBillingAddress, baseShippingAddress]);

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

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

  it("returns only SHIPPING addresses when addressType filter is provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseShippingAddress]);

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

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

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

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

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

  it("includes both default and non-default addresses in results", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseBillingAddress, baseShippingAddress]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      const defaults = result.value.items.map((a) => a.isDefault);
      expect(defaults).toContain(true);
      expect(defaults).toContain(false);
    }
  });
});
