import type { Transaction } from "../generated/kysely-tailordb";
import { PipelineLockedError } from "./errors.generated";

/**
 * Locked pipelines keep the lane template seeded at creation time (see
 * createPipeline's `stages` input) — their stages are not editable by
 * stage-mutation commands. Every stage-mutation command must call one of
 * these guards so the lock rule lives in exactly one place.
 */
export function pipelineLockError(
  locked: boolean | null | undefined,
  pipelineId: string,
): InstanceType<typeof PipelineLockedError> | null {
  return locked ? new PipelineLockedError(pipelineId) : null;
}

/** Variant for commands that haven't loaded the Pipeline row yet. */
export async function loadPipelineLockError(
  db: Transaction,
  pipelineId: string,
): Promise<InstanceType<typeof PipelineLockedError> | null> {
  const pipeline = await db
    .selectFrom("Pipeline")
    .select(["locked"])
    .where("id", "=", pipelineId)
    .executeTakeFirst();
  return pipelineLockError(pipeline?.locked, pipelineId);
}
