import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseBillingAddress]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    const nonDefaultAddress = { ...baseShippingAddress, isDefault: false };
    mock.enqueueResults([nonDefaultAddress]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

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