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 {
  softLockedPeriodClose,
  underReviewPeriodClose,
  inProgressPeriodClose,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./finalCloseAndLockPeriod";

describe("finalCloseAndLockPeriod", () => {
  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 UNDER_REVIEW status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(underReviewPeriodClose);

    const result = await run(db, { id: underReviewPeriodClose.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("transitions SOFT_LOCKED PeriodClose to PERMANENTLY_CLOSED with completionPercentage 100", async () => {
    const updatedPeriodClose = {
      ...softLockedPeriodClose,
      status: "PERMANENTLY_CLOSED",
      completionPercentage: 100,
      finalizedByUserId: commandCtx.actorId,
    };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(softLockedPeriodClose);
    spies.update.mockReturnValueOnce(updatedPeriodClose);
    spies.update.mockReturnValueOnce({ status: "PERMANENTLY_CLOSED" });

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

    const value = expectOk(result);
    expect(value.periodClose.status).toBe("PERMANENTLY_CLOSED");
    expect(value.periodClose.completionPercentage).toBe(100);
    expect(value.periodClose.finalizedByUserId).toBe(commandCtx.actorId);
  });

  it("also updates the associated AccountingPeriod to PERMANENTLY_CLOSED", async () => {
    const updatedPeriodClose = {
      ...softLockedPeriodClose,
      status: "PERMANENTLY_CLOSED",
      completionPercentage: 100,
    };
    const updatedAccountingPeriod = { status: "PERMANENTLY_CLOSED" };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(softLockedPeriodClose);
    spies.update.mockReturnValueOnce(updatedPeriodClose);
    spies.update.mockReturnValueOnce(updatedAccountingPeriod);

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

    expectOk(result);
    expect(spies.update).toHaveBeenCalledTimes(2);
  });

  it("emits audit event recording status transition from SOFT_LOCKED to PERMANENTLY_CLOSED", async () => {
    const updatedPeriodClose = {
      ...softLockedPeriodClose,
      status: "PERMANENTLY_CLOSED",
      completionPercentage: 100,
    };
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(softLockedPeriodClose);
    spies.update.mockReturnValueOnce(updatedPeriodClose);
    spies.update.mockReturnValueOnce({ status: "PERMANENTLY_CLOSED" });

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

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