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

/**
 * Function: closePeriod
 *
 * Closes an OPEN accounting period while allowing later reopening.
 */
export async function run(db: Transaction, input: ClosePeriodInput, _ctx: CommandContext) {
  const result = await executeTransition({
    db,
    tableName: "AccountingPeriod",
    statusField: "status",
    id: input.id,
    transition: "closePeriod",
    lifecycle: accountingPeriodLifecycle,
    errors: {
      notFound: AccountingPeriodNotFoundError,
      invalidTransition: InvalidStatusTransitionError,
    },
  });
  if (!result.ok) return result;
  return ok({ accountingPeriod: result.value });
}
