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 {
  executedAllocationCycle,
  validatedAllocationCycle,
  baseAccountingPeriod,
  closedAccountingPeriod,
  baseAllocationResult,
  activeCostElement,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./postAllocationCycle";

describe("postAllocationCycle", () => {
  it("posts an EXECUTED allocation cycle transitioning it to POSTED status", async () => {
    const posted = { ...executedAllocationCycle, status: "POSTED" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(executedAllocationCycle) // cycle lookup
      .mockReturnValueOnce(baseAccountingPeriod) // period lookup
      .mockReturnValueOnce([baseAllocationResult]) // allocation results
      .mockReturnValueOnce(activeCostElement); // cost element lookup
    spies.insert.mockReturnValueOnce({ id: "journal-entry-1" });
    spies.update.mockReturnValueOnce(posted);

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

    const value = expectOk(result);
    expect(value.allocationCycle.status).toBe("POSTED");
    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 EXECUTED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(validatedAllocationCycle);

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

    expectErr(result, InvalidStateError);
  });

  it("returns error when accounting period is CLOSED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(executedAllocationCycle)
      .mockReturnValueOnce(closedAccountingPeriod);

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

    expectErr(result, PeriodNotOpenError);
  });

  it("returns error when accounting period is PERMANENTLY_CLOSED", async () => {
    const permClosedPeriod = {
      ...baseAccountingPeriod,
      id: "period-perm-closed",
      status: "PERMANENTLY_CLOSED",
    };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(executedAllocationCycle).mockReturnValueOnce(permClosedPeriod);

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

    expectErr(result, PeriodNotOpenError);
  });

  it("emits audit event recording the status transition and acting user", async () => {
    const posted = { ...executedAllocationCycle, status: "POSTED" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(executedAllocationCycle)
      .mockReturnValueOnce(baseAccountingPeriod)
      .mockReturnValueOnce([baseAllocationResult])
      .mockReturnValueOnce(activeCostElement);
    spies.insert.mockReturnValueOnce({ id: "journal-entry-1" });
    spies.update.mockReturnValueOnce(posted);

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

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