import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { VarianceReportNotFoundError, InvalidStateError } from "../lib/errors.generated";
import { baseVarianceReport, finalVarianceReport } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./finalizeVarianceReport";

describe("finalizeVarianceReport", () => {
  it("finalizes a DRAFT variance report transitioning it to FINAL status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedReport = { ...baseVarianceReport, status: "FINAL", updatedAt: new Date() };
    spies.select.mockReturnValueOnce(baseVarianceReport);
    spies.update.mockReturnValueOnce(updatedReport);

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

    const value = expectOk(result);
    expect(value.varianceReport).toEqual(updatedReport);
  });

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

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

    expectErr(result, VarianceReportNotFoundError);
  });

  it("returns error when variance report is already FINAL", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(finalVarianceReport);

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

    expectErr(result, InvalidStateError);
  });

  it("finalized report cannot be transitioned back to DRAFT", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(finalVarianceReport);

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

    expectErr(result, InvalidStateError);
  });

  it("emits audit event recording the status transition and acting user", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedReport = { ...baseVarianceReport, status: "FINAL", updatedAt: new Date() };
    spies.select.mockReturnValueOnce(baseVarianceReport);
    spies.update.mockReturnValueOnce(updatedReport);

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

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