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

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

  it("deletes an address", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseBillingAddress]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.success).toBe(true);
    }
    expect(mock.deletes.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" }, 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseBillingAddress]);

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

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

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(AddressInUseError);
    }
    // Should not have called delete
    expect(mock.deletes).toHaveLength(0);
  });

  it("deleting default does not promote another", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    // baseBillingAddress has isDefault: true
    mock.enqueueResults([baseBillingAddress]);

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

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

    expect(result.ok).toBe(true);
    expect(mock.deletes.length).toBeGreaterThan(0);
    // No update call to promote another address
    expect(mock.updates).toHaveLength(0);
  });
});
