import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { ChartOfAccountsNotFoundError, InvalidStateTransitionError } from "../lib/errors.generated";
import { baseDraftCoa, baseActiveCoa, baseArchivedCoa } from "../testing/fixtures";
import { run } from "./deactivateChartOfAccounts";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

describe("deactivateChartOfAccounts", () => {
  it("returns error when CoA does not exist", 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(ChartOfAccountsNotFoundError);
    }
  });

  it("returns error when CoA is DRAFT", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftCoa);

    const result = await run(db, { id: baseDraftCoa.id }, ctx);

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

  it("returns error when CoA is already ARCHIVED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseArchivedCoa);

    const result = await run(db, { id: baseArchivedCoa.id }, ctx);

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

  it("archives an ACTIVE CoA", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const archivedCoa = { ...baseActiveCoa, status: "ARCHIVED" };
    spies.select.mockReturnValueOnce(baseActiveCoa);
    spies.update.mockReturnValue(archivedCoa);

    const result = await run(db, { id: baseActiveCoa.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.chartOfAccounts.status).toBe("ARCHIVED");
    }
  });
});
