import { err, ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { DB } from "../generated/kysely-tailordb";
import { PipelineNotFoundError } from "../lib/errors.generated";

export interface ListPipelineStagesByPipelineInput {
  pipelineId: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListPipelineStagesByPipelineInput) {
  const pipeline = await db
    .selectFrom("Pipeline")
    .selectAll()
    .where("id", "=", input.pipelineId)
    .executeTakeFirst();

  if (!pipeline) {
    return err(new PipelineNotFoundError(input.pipelineId));
  }

  const stages = await db
    .selectFrom("PipelineStage")
    .selectAll()
    .where("pipelineId", "=", input.pipelineId)
    .orderBy("position", "asc")
    .execute();

  return ok({ stages });
}
