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 ListPipelineLabelsByPipelineInput {
  pipelineId: string;
}

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

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

  const labels = await db
    .selectFrom("PipelineLabel")
    .selectAll()
    .where("pipelineId", "=", input.pipelineId)
    .orderBy("name", "asc")
    .execute();

  return ok({ labels });
}
