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

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

describe("activateChartOfAccounts", () => {
  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 already ACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveCoa);

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

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

  it("returns error when CoA is 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("returns error when another ACTIVE CoA exists for the same company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseDraftCoa) // CoA lookup
      .mockReturnValueOnce(baseActiveCoa); // existing ACTIVE CoA for same company

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

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

  it("activates a DRAFT CoA", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activatedCoa = { ...baseDraftCoa, status: "ACTIVE" };
    spies.select
      .mockReturnValueOnce(baseDraftCoa) // CoA lookup
      .mockReturnValueOnce(undefined); // no existing ACTIVE CoA
    spies.update.mockReturnValue(activatedCoa);

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

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