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

export interface DeletePipelineStageInput {
  stageId: string;
}

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

  const stage = await db
    .selectFrom("PipelineStage")
    .selectAll()
    .where("id", "=", input.stageId)
    .forUpdate()
    .executeTakeFirst();

  if (!stage) {
    return err(new StageNotFoundError(input.stageId));
  }

  const lockError = await loadPipelineLockError(db, stage.pipelineId);
  if (lockError) {
    return err(lockError);
  }

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

  if (item) {
    return err(new StageHasItemsError(input.stageId));
  }

  await db.deleteFrom("PipelineStage").where("id", "=", input.stageId).execute();

  return ok({ stage });
}
