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

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

  it("deletes an existing bank account", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDefaultBankAccount);

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

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

  it("deletes default bank account without promoting another", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // The account being deleted is the default one
    spies.select.mockReturnValueOnce({ ...baseDefaultBankAccount, isDefault: true });

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.deleted).toBe(true);
    }
    expect(spies.delete).toHaveBeenCalled();
    // No promotion logic — no additional update calls
    expect(spies.update).not.toHaveBeenCalled();
  });

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