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 FinalCloseAndLockPeriodInput {
  id: string;
}

/**
 * Function: finalCloseAndLockPeriod
 *
 * Transitions a PeriodClose record from SOFT_LOCKED to PERMANENTLY_CLOSED status,
 * making the period fully immutable — no further journal entries allowed regardless of role.
 * Also transitions the underlying AccountingPeriod to PERMANENTLY_CLOSED.
 * Sets completionPercentage to 100% and records the operator's userId.
 */
export async function run(
  db: Transaction,
  input: FinalCloseAndLockPeriodInput,
  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 SOFT_LOCKED
  if (periodClose.status !== "SOFT_LOCKED") {
    return err(new InvalidStatusTransitionError(id));
  }

  // 3. Transition PeriodClose to PERMANENTLY_CLOSED with completionPercentage 100
  const updated = await db
    .updateTable("PeriodClose")
    .set({
      status: "PERMANENTLY_CLOSED",
      completionPercentage: 100,
      finalizedByUserId: ctx.actorId,
      updatedAt: new Date(),
    })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  // 4. Also transition the associated AccountingPeriod to PERMANENTLY_CLOSED
  await db
    .updateTable("AccountingPeriod")
    .set({
      status: "PERMANENTLY_CLOSED",
      updatedAt: new Date(),
    })
    .where("id", "=", periodClose.accountingPeriodId)
    .returningAll()
    .executeTakeFirstOrThrow();

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

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