import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  AllocationCycleNotFoundError,
  InvalidStateError,
  PeriodNotOpenError,
} from "../lib/errors.generated";
import {
  postedAllocationCycle,
  baseAllocationCycle,
  validatedAllocationCycle,
  executedAllocationCycle,
  reversedAllocationCycle,
  baseAccountingPeriod,
  closedAccountingPeriod,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./reverseAllocationCycle";

describe("reverseAllocationCycle", () => {
  it("reverses a POSTED allocation cycle transitioning it to REVERSED status", async () => {
    const reversed = { ...postedAllocationCycle, status: "REVERSED" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(postedAllocationCycle) // cycle lookup
      .mockReturnValueOnce(baseAccountingPeriod) // period lookup
      .mockReturnValueOnce([
        {
          id: "journal-entry-1",
          referenceNumber: "ALLOC-cycle-1-result-1",
          sourceDocumentReference: `AllocationCycle:${postedAllocationCycle.id}`,
        },
      ]); // original postings
    spies.insert.mockReturnValueOnce({ id: "reversal-entry-1" });
    spies.update.mockReturnValueOnce({ id: "journal-entry-1", status: "REVERSED" });
    spies.update.mockReturnValueOnce(reversed);

    const result = await run(db, { allocationCycleId: postedAllocationCycle.id }, commandCtx);

    const value = expectOk(result);
    expect(value.allocationCycle.status).toBe("REVERSED");
    expect(spies.insert).toHaveBeenCalled();
  });

  it("returns error when allocation cycle does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { allocationCycleId: "missing-id" }, commandCtx);

    expectErr(result, AllocationCycleNotFoundError);
  });

  it("returns error when allocation cycle is not in POSTED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(executedAllocationCycle);

    const result = await run(db, { allocationCycleId: executedAllocationCycle.id }, commandCtx);

    expectErr(result, InvalidStateError);
  });

  it("returns error when allocation cycle is already REVERSED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(reversedAllocationCycle);

    const result = await run(db, { allocationCycleId: reversedAllocationCycle.id }, commandCtx);

    expectErr(result, InvalidStateError);
  });

  it("returns error when reversal period is not OPEN or FUTURE_ENTERABLE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(postedAllocationCycle)
      .mockReturnValueOnce(closedAccountingPeriod);

    const result = await run(db, { allocationCycleId: postedAllocationCycle.id }, commandCtx);

    expectErr(result, PeriodNotOpenError);
  });

  it("returns error when allocation cycle is in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseAllocationCycle);

    const result = await run(db, { allocationCycleId: baseAllocationCycle.id }, commandCtx);

    expectErr(result, InvalidStateError);
  });

  it("returns error when allocation cycle is in VALIDATED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(validatedAllocationCycle);

    const result = await run(db, { allocationCycleId: validatedAllocationCycle.id }, commandCtx);

    expectErr(result, InvalidStateError);
  });

  it("emits audit event recording the status transition and acting user", async () => {
    const reversed = { ...postedAllocationCycle, status: "REVERSED" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(postedAllocationCycle)
      .mockReturnValueOnce(baseAccountingPeriod)
      .mockReturnValueOnce([
        {
          id: "journal-entry-1",
          referenceNumber: "ALLOC-cycle-1-result-1",
          sourceDocumentReference: `AllocationCycle:${postedAllocationCycle.id}`,
        },
      ]);
    spies.insert.mockReturnValueOnce({ id: "reversal-entry-1" });
    spies.update.mockReturnValueOnce({ id: "journal-entry-1", status: "REVERSED" });
    spies.update.mockReturnValueOnce(reversed);

    const result = await run(db, { allocationCycleId: postedAllocationCycle.id }, commandCtx);

    expectOk(result);
    expect(spies.update).toHaveBeenCalled();
  });
});
