import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  FinancialStatementNotFoundError,
  InvalidStatusTransitionError,
} from "../lib/errors.generated";
import { baseFinancialStatement, finalizedFinancialStatement } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./finalizeFinancialStatement";

describe("finalizeFinancialStatement", () => {
  it("returns error when financial statement does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // statement lookup

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

    expectErr(result, FinancialStatementNotFoundError);
  });

  it("returns error when financial statement is already FINALIZED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(finalizedFinancialStatement); // statement lookup

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

    expectErr(result, InvalidStatusTransitionError);
  });

  it("transitions DRAFT statement to FINALIZED with finalizedAt set", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const finalizedResult = {
      ...baseFinancialStatement,
      status: "FINALIZED",
      finalizedAt: new Date(),
      updatedAt: new Date(),
    };
    spies.select.mockReturnValueOnce(baseFinancialStatement); // statement lookup
    spies.update.mockReturnValueOnce(finalizedResult); // update result

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

    const value = expectOk(result);
    expect(value.financialStatement.status).toBe("FINALIZED");
    expect(value.financialStatement.finalizedAt).toBeDefined();
  });

  it("emits audit event recording status transition from DRAFT to FINALIZED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const finalizedResult = {
      ...baseFinancialStatement,
      status: "FINALIZED",
      finalizedAt: new Date(),
      updatedAt: new Date(),
    };
    spies.select.mockReturnValueOnce(baseFinancialStatement); // statement lookup
    spies.update.mockReturnValueOnce(finalizedResult); // update result

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

    const value = expectOk(result);
    expect(value.auditTrail).toBeDefined();
    expect(value.auditTrail).toContainEqual(
      expect.objectContaining({
        type: "STATUS_TRANSITION",
        from: "DRAFT",
        to: "FINALIZED",
        actorId: commandCtx.actorId,
      }),
    );
  });
});
