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

export interface ListPipelineLabelsByItemInput {
  itemId: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListPipelineLabelsByItemInput) {
  const item = await db
    .selectFrom("PipelineItem")
    .selectAll()
    .where("id", "=", input.itemId)
    .executeTakeFirst();

  if (!item) {
    return err(new ItemNotFoundError(input.itemId));
  }

  const labels = await db
    .selectFrom("PipelineLabel")
    .innerJoin("PipelineItemLabel", "PipelineItemLabel.labelId", "PipelineLabel.id")
    .selectAll("PipelineLabel")
    .where("PipelineItemLabel.itemId", "=", input.itemId)
    .orderBy("PipelineLabel.name", "asc")
    .execute();

  return ok({ labels });
}
