import { ok, executeTransition, type CommandContext } from "@tailor-platform/erp-kit/core";
import { accountingPeriodLifecycle } from "../db/accountingPeriod.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  AccountingPeriodNotFoundError,
  InvalidStatusTransitionError,
} from "../lib/errors.generated";

export interface PermanentlyClosePeriodInput {
  id: string;
}

/**
 * Function: permanentlyClosePeriod
 *
 * Irreversibly closes a CLOSED accounting period after final adjustments.
 */
export async function run(
  db: Transaction,
  input: PermanentlyClosePeriodInput,
  _ctx: CommandContext,
) {
  const result = await executeTransition({
    db,
    tableName: "AccountingPeriod",
    statusField: "status",
    id: input.id,
    transition: "permanentlyClosePeriod",
    lifecycle: accountingPeriodLifecycle,
    errors: {
      notFound: AccountingPeriodNotFoundError,
      invalidTransition: InvalidStatusTransitionError,
    },
  });
  if (!result.ok) return result;
  return ok({ accountingPeriod: result.value });
}
