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 {
  AccountNotFoundError,
  InvalidStateTransitionError,
  OpenBalancesExistError,
} from "../lib/errors.generated";
import { baseActiveAccount, baseInactiveAccount } from "../testing/fixtures";
import { run } from "./deactivateAccount";

const ctx: CommandContext = {
  actorId: "test-actor",
  permissions: ["coa-management:coa:deactivateAccount"],
};

describe("deactivateAccount", () => {
  it("returns error when account does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

    expect(result.ok).toBe(false);
    if (!result.ok) expect(result.error).toBeInstanceOf(AccountNotFoundError);
  });

  it("returns error when account is not active", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseInactiveAccount]);

    const result = await mock.withTx((trx) => run(trx, { id: baseInactiveAccount.id }, ctx));

    expect(result.ok).toBe(false);
    if (!result.ok) expect(result.error).toBeInstanceOf(InvalidStateTransitionError);
  });

  it("deactivates an active account", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivated = { ...baseActiveAccount, status: "INACTIVE" as const };
    mock.enqueueResults([baseActiveAccount], [deactivated]);

    const result = await mock.withTx((trx) => run(trx, { id: baseActiveAccount.id }, ctx));

    expect(result.ok).toBe(true);
    if (result.ok) expect(result.value.account.status).toBe("INACTIVE");
  });

  it("returns error when GL hook reports open balances", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveAccount]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: baseActiveAccount.id, preDeactivationHook: () => Promise.resolve(false) },
        ctx,
      ),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) expect(result.error).toBeInstanceOf(OpenBalancesExistError);
  });
});
