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 ListPipelineStageTransitionsByItemInput {
  itemId: string;
}

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

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

  const transitions = await db
    .selectFrom("PipelineStageTransition")
    .selectAll()
    .where("itemId", "=", input.itemId)
    .orderBy("createdAt", "asc")
    .execute();

  return ok({ transitions });
}
