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

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

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

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

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

    const result = await run(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);
    }
  });
});
