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

export interface ListPipelineItemsByStageInput {
  stageId: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListPipelineItemsByStageInput) {
  const stage = await db
    .selectFrom("PipelineStage")
    .selectAll()
    .where("id", "=", input.stageId)
    .executeTakeFirst();

  if (!stage) {
    return err(new StageNotFoundError(input.stageId));
  }

  const items = await db
    .selectFrom("PipelineItem")
    .selectAll()
    .where("stageId", "=", input.stageId)
    .orderBy("position", "asc")
    .execute();

  return ok({ items });
}
