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 { baseSecondBankAccount } from "../testing/fixtures";
import { run } from "./setDefaultPartnerBankAccount";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("sets account as default", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseSecondBankAccount);
    // update unset others — no return needed
    spies.update.mockReturnValueOnce(undefined);
    // update set this one
    spies.update.mockReturnValueOnce({ ...baseSecondBankAccount, isDefault: true });

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.bankAccount.isDefault).toBe(true);
    }
  });

  it("unsets previous default account", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseSecondBankAccount);
    spies.update.mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce({ ...baseSecondBankAccount, isDefault: true });

    await run(db, { id: "bank-2" }, ctx);

    // First update call should set isDefault: false on other accounts
    expect(spies.set).toHaveBeenCalledWith(expect.objectContaining({ isDefault: false }));
    // Second update call should set isDefault: true on this account
    expect(spies.set).toHaveBeenCalledWith(expect.objectContaining({ isDefault: true }));
  });

  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);
    }
  });
});
