import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } 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 { db, spies } = createMockDb<Transaction>();
    const updatedAddress = {
      ...baseShippingAddress,
      isDefault: true,
      updatedAt: new Date(),
    };

    spies.select.mockReturnValueOnce(baseShippingAddress); // Address lookup
    spies.update.mockReturnValue(updatedAddress);

    const result = await run(db, { id: "address-2" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.address.isDefault).toBe(true);
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("unsets previous default of same type", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const newDefault = {
      ...baseShippingAddress,
      isDefault: true,
      updatedAt: new Date(),
    };

    spies.select.mockReturnValueOnce(baseShippingAddress); // Address lookup
    spies.update
      .mockReturnValueOnce(undefined) // Unset previous defaults (execute)
      .mockReturnValueOnce(newDefault); // Set new default

    const result = await run(db, { id: "address-2" });

    expect(result.ok).toBe(true);
    // Two update calls: one to unset previous defaults, one to set new default
    expect(spies.update).toHaveBeenCalled();
  });

  it("returns error when address not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // Address not found

    const result = await run(db, { id: "nonexistent" });

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