import { ok, executeTransition, type CommandContext } from "@tailor-platform/erp-kit/core";
import { allocationCycleLifecycle } from "../db/allocationCycle.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { AllocationCycleNotFoundError, InvalidStateError } from "../lib/errors.generated";

export interface InvalidateAllocationCycleInput {
  allocationCycleId: string;
}

export async function run(
  db: Transaction,
  input: InvalidateAllocationCycleInput,
  ctx: CommandContext,
) {
  void ctx;
  const result = await executeTransition({
    db,
    tableName: "AllocationCycle",
    statusField: "status",
    id: input.allocationCycleId,
    transition: "invalidate",
    lifecycle: allocationCycleLifecycle,
    errors: { notFound: AllocationCycleNotFoundError, invalidTransition: InvalidStateError },
  });
  if (!result.ok) return result;
  return ok({ allocationCycle: result.value });
}
