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

describe("approveAndLockPeriod", () => {
  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 in NOT_STARTED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePeriodClose);

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

    expectErr(result, InvalidStatusTransitionError);
  });

  it("returns error when PeriodClose is in IN_PROGRESS status", 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 already SOFT_LOCKED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(softLockedPeriodClose);

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

    expectErr(result, InvalidStatusTransitionError);
  });

  it("returns error when user lacks required permissions", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(underReviewPeriodClose);

    const noPermCtx = { actorId: "test-actor", permissions: [] as string[] };
    const result = await run(db, { id: underReviewPeriodClose.id }, noPermCtx);

    expectErr(result, InsufficientPermissionsError);
  });

  it("transitions UNDER_REVIEW PeriodClose to SOFT_LOCKED with approvedByUserId and completionPercentage", async () => {
    const updatedPeriodClose = {
      ...underReviewPeriodClose,
      status: "SOFT_LOCKED",
      completionPercentage: 87,
      approvedByUserId: commandCtx.actorId,
    };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(underReviewPeriodClose);
    spies.update.mockReturnValueOnce(updatedPeriodClose);

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

    const value = expectOk(result);
    expect(value.periodClose.status).toBe("SOFT_LOCKED");
    expect(value.periodClose.approvedByUserId).toBe(commandCtx.actorId);
    expect(value.periodClose.completionPercentage).toBe(87);
  });

  it("emits audit event recording status transition from UNDER_REVIEW to SOFT_LOCKED", async () => {
    const updatedPeriodClose = {
      ...underReviewPeriodClose,
      status: "SOFT_LOCKED",
      completionPercentage: 87,
      approvedByUserId: commandCtx.actorId,
    };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(underReviewPeriodClose);
    spies.update.mockReturnValueOnce(updatedPeriodClose);

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

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