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

export interface BeginCloseInput {
  id: string;
}

/**
 * Function: beginClose
 *
 * Transitions a PeriodClose record from NOT_STARTED to IN_PROGRESS status,
 * indicating that the close checklist execution has begun.
 */
export async function run(db: Transaction, input: BeginCloseInput, 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 NOT_STARTED
  if (periodClose.status !== "NOT_STARTED") {
    return err(new InvalidStatusTransitionError(id));
  }

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

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

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