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

describe("setDefaultPartnerAddress", () => {
  it("sets address as default", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedAddress = {
      ...baseShippingAddress,
      isDefault: true,
      updatedAt: new Date(),
    };
    mock.enqueueResults([baseShippingAddress], [], [updatedAddress]);

    const result = await mock.withTx((trx) => run(trx, { id: "address-2" }));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.address.isDefault).toBe(true);
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("unsets previous default of same type", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const newDefault = {
      ...baseShippingAddress,
      isDefault: true,
      updatedAt: new Date(),
    };
    mock.enqueueResults([baseShippingAddress], [], [newDefault]);

    const result = await mock.withTx((trx) => run(trx, { id: "address-2" }));

    expect(result.ok).toBe(true);
    // Two update calls: one to unset previous defaults, one to set new default
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("returns error when address not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { id: "nonexistent" }));

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