import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  PeriodCloseNotFoundError,
  PeriodPermanentlyClosedError,
  InvalidStatusTransitionError,
} from "../lib/errors.generated";

export interface RevertSoftLockInput {
  id: string;
}

/**
 * Function: revertSoftLock
 *
 * Transitions a PeriodClose record from SOFT_LOCKED back to IN_PROGRESS status,
 * allowing the close workflow to be revisited when errors are discovered.
 * Only permitted before permanent close.
 */
export async function run(db: Transaction, input: RevertSoftLockInput, ctx: CommandContext) {
  const { id } = input;

  // 1. Find PeriodClose record
  const periodClose = await db
    .selectFrom("PeriodClose")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!periodClose) {
    return err(new PeriodCloseNotFoundError(id));
  }

  // 2. Reject permanently closed periods
  if (periodClose.status === "PERMANENTLY_CLOSED") {
    return err(new PeriodPermanentlyClosedError(id));
  }

  // 3. Validate status is SOFT_LOCKED
  if (periodClose.status !== "SOFT_LOCKED") {
    return err(new InvalidStatusTransitionError(id));
  }

  // 4. Transition back to IN_PROGRESS and record acting user
  const updated = await db
    .updateTable("PeriodClose")
    .set({
      status: "IN_PROGRESS",
      updatedAt: new Date(),
    })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  // 5. Emit audit event recording status transition
  const auditTrail = [
    {
      type: "STATUS_TRANSITION",
      from: "SOFT_LOCKED",
      to: "IN_PROGRESS",
      actorId: ctx.actorId,
    },
  ];

  return ok({ periodClose: updated, auditTrail });
}
