import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { PeriodCloseNotFoundError, InvalidStatusTransitionError } from "../lib/errors.generated";
import {
  basePeriodClose,
  inProgressPeriodClose,
  subledgersVerifiedPeriodClose,
  permanentlyClosedPeriodClose,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./beginClose";

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

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

    expectErr(result, PeriodCloseNotFoundError);
  });

  it("returns error when PeriodClose is already IN_PROGRESS", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inProgressPeriodClose);

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

    expectErr(result, InvalidStatusTransitionError);
  });

  it("returns error when PeriodClose is in SUBLEDGERS_VERIFIED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(subledgersVerifiedPeriodClose);

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

    expectErr(result, InvalidStatusTransitionError);
  });

  it("returns error when PeriodClose is in PERMANENTLY_CLOSED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(permanentlyClosedPeriodClose);

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

    expectErr(result, InvalidStatusTransitionError);
  });

  it("transitions NOT_STARTED PeriodClose to IN_PROGRESS", async () => {
    const updatedPeriodClose = {
      ...basePeriodClose,
      status: "IN_PROGRESS",
      completionPercentage: 12,
    };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePeriodClose);
    spies.update.mockReturnValueOnce(updatedPeriodClose);

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

    const value = expectOk(result);
    expect(value.periodClose.status).toBe("IN_PROGRESS");
  });

  it("records the acting user who began the close", async () => {
    const updatedPeriodClose = {
      ...basePeriodClose,
      status: "IN_PROGRESS",
      completionPercentage: 12,
    };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePeriodClose);
    spies.update.mockReturnValueOnce(updatedPeriodClose);

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

    const value = expectOk(result);
    expect(value.auditTrail).toBeDefined();
    expect(value.auditTrail[0].actorId).toBe(commandCtx.actorId);
  });

  it("emits audit event recording status transition from NOT_STARTED to IN_PROGRESS and acting user", async () => {
    const updatedPeriodClose = {
      ...basePeriodClose,
      status: "IN_PROGRESS",
      completionPercentage: 12,
    };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePeriodClose);
    spies.update.mockReturnValueOnce(updatedPeriodClose);

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

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