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 { BankAccountNotFoundError } from "../lib/errors.generated";
import { baseDefaultBankAccount } from "../testing/fixtures";
import { run } from "./deletePartnerBankAccount";

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

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

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.deleted).toBe(true);
    }
    expect(mock.deletes.length).toBeGreaterThan(0);
  });

  it("deletes default bank account without promoting another", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    // The account being deleted is the default one
    mock.enqueueResults([{ ...baseDefaultBankAccount, isDefault: true }]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.deleted).toBe(true);
    }
    expect(mock.deletes.length).toBeGreaterThan(0);
    // No promotion logic — no additional update calls
    expect(mock.updates).toHaveLength(0);
  });

  it("returns error when account 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(BankAccountNotFoundError);
    }
  });
});
