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

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