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

export interface DeletePipelineItemInput {
  itemId: string;
}

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

  const item = await db
    .selectFrom("PipelineItem")
    .selectAll()
    .where("id", "=", input.itemId)
    .forUpdate()
    .executeTakeFirst();

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

  // No DB-level cascade exists, so dependent rows are removed explicitly to
  // avoid orphaned join/audit records (mirrors deletePipelineLabel's manual cascade).
  await db.deleteFrom("PipelineItemLabel").where("itemId", "=", input.itemId).execute();
  await db.deleteFrom("PipelineItemComment").where("itemId", "=", input.itemId).execute();
  await db.deleteFrom("PipelineItemChange").where("itemId", "=", input.itemId).execute();
  await db.deleteFrom("PipelineStageTransition").where("itemId", "=", input.itemId).execute();
  await db.deleteFrom("PipelineItem").where("id", "=", input.itemId).execute();

  return ok({ item });
}
