import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { AddressNotFoundError, AddressInUseError } from "../lib/errors.generated";
import { baseBillingAddress } from "../testing/fixtures";
import { run } from "./deletePartnerAddress";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

describe("deletePartnerAddress", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["business-partner:deletePartnerAddress"],
  };

  it("deletes an address", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseBillingAddress);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.success).toBe(true);
    }
    expect(spies.delete).toHaveBeenCalled();
  });

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

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

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

  it("returns error when address is referenced on transactions", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseBillingAddress);

    const referenceChecker = {
      isAddressReferenced: () => Promise.resolve(true),
    };

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

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(AddressInUseError);
    }
    // Should not have called delete
    expect(spies.delete).not.toHaveBeenCalled();
  });

  it("deleting default does not promote another", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // baseBillingAddress has isDefault: true
    spies.select.mockReturnValueOnce(baseBillingAddress);

    const referenceChecker = {
      isAddressReferenced: () => Promise.resolve(false),
    };

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

    expect(result.ok).toBe(true);
    expect(spies.delete).toHaveBeenCalled();
    // No update call to promote another address
    expect(spies.update).not.toHaveBeenCalled();
  });
});
