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 { baseSecondBankAccount } from "../testing/fixtures";
import { run } from "./setDefaultPartnerBankAccount";

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

  it("sets account as default", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseSecondBankAccount],
      [],
      [{ ...baseSecondBankAccount, isDefault: true }],
    );

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseSecondBankAccount],
      [],
      [{ ...baseSecondBankAccount, isDefault: true }],
    );

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

    // First update call should set isDefault: false on other accounts
    expect(mock.updates[0].updateValues()).toEqual(expect.objectContaining({ isDefault: false }));
    // Second update call should set isDefault: true on this account
    expect(mock.updates[1].updateValues()).toEqual(expect.objectContaining({ isDefault: true }));
  });

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