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

export interface ApproveAndLockPeriodInput {
  id: string;
}

/**
 * Function: approveAndLockPeriod
 *
 * Transitions a PeriodClose record from UNDER_REVIEW to SOFT_LOCKED status.
 * Prevents accounting team from posting new journal entries while allowing
 * advisor/auditor roles to post final adjustments. Records the approver's userId.
 */
export async function run(db: Transaction, input: ApproveAndLockPeriodInput, 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. Validate status is UNDER_REVIEW
  if (periodClose.status !== "UNDER_REVIEW") {
    return err(new InvalidStatusTransitionError(id));
  }

  // 3. Check permissions
  if (
    !ctx.permissions.includes("finance-ledger:approveAndLockPeriod") &&
    !ctx.permissions.includes("finance-ledger:*")
  ) {
    return err(new InsufficientPermissionsError(id));
  }

  // 4. Transition to SOFT_LOCKED and record approver
  const updated = await db
    .updateTable("PeriodClose")
    .set({
      status: "SOFT_LOCKED",
      completionPercentage: 87,
      approvedByUserId: ctx.actorId,
      updatedAt: new Date(),
    })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

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

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