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

export interface FinalizeVarianceReportInput {
  varianceReportId: string;
}

export async function run(
  db: Transaction,
  input: FinalizeVarianceReportInput,
  ctx: CommandContext,
) {
  void ctx;
  const result = await executeTransition({
    db,
    tableName: "VarianceReport",
    statusField: "status",
    id: input.varianceReportId,
    transition: "finalize",
    lifecycle: varianceReportLifecycle,
    errors: { notFound: VarianceReportNotFoundError, invalidTransition: InvalidStateError },
  });
  if (!result.ok) return result;
  return ok({ varianceReport: result.value });
}
