import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { NoAddressOfTypeError, NoDefaultAddressError } from "../lib/errors.generated";
import { baseBillingAddress, baseShippingAddress } from "../testing/fixtures";
import { run } from "./getDefaultPartnerAddress";

describe("getDefaultPartnerAddress", () => {
  it("returns default address when one exists", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseBillingAddress]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.partnerAddress).toEqual(baseBillingAddress);
    }
  });

  it("returns error when addresses of the type exist but no default is set", async () => {
    const { db, spies } = createMockDb<DB>();
    const nonDefaultAddress = { ...baseShippingAddress, isDefault: false };
    spies.select.mockReturnValue([nonDefaultAddress]);

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

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(NoDefaultAddressError);
    }
  });

  it("returns error when partner has no addresses of the given type", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([]);

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

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(NoAddressOfTypeError);
    }
  });
});
