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

export interface DeletePipelineLabelInput {
  labelId: string;
}

export async function run(db: Transaction, input: DeletePipelineLabelInput, ctx: CommandContext) {
  void ctx;

  const label = await db
    .selectFrom("PipelineLabel")
    .selectAll()
    .where("id", "=", input.labelId)
    .forUpdate()
    .executeTakeFirst();

  if (!label) {
    return err(new LabelNotFoundError(input.labelId));
  }

  await db.deleteFrom("PipelineItemLabel").where("labelId", "=", input.labelId).execute();
  await db.deleteFrom("PipelineLabel").where("id", "=", input.labelId).execute();

  return ok({ label });
}
