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

export interface DeleteCostCenterHierarchyNodeInput {
  nodeId: string;
}

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

  // Validate node exists
  const node = await db
    .selectFrom("CostCenterHierarchyNode")
    .where("id", "=", input.nodeId)
    .selectAll()
    .forUpdate()
    .executeTakeFirst();

  if (!node) {
    return err(new NodeNotFoundError(input.nodeId));
  }

  // Validate no child nodes exist
  const childNode = await db
    .selectFrom("CostCenterHierarchyNode")
    .where("parentNodeId", "=", input.nodeId)
    .selectAll()
    .executeTakeFirst();

  if (childNode) {
    return err(new NodeHasChildrenError(input.nodeId));
  }

  // Validate no cost centers are assigned to this node
  const assignedCostCenter = await db
    .selectFrom("CostCenter")
    .where("hierarchyNodeId", "=", input.nodeId)
    .selectAll()
    .executeTakeFirst();

  if (assignedCostCenter) {
    return err(new NodeHasAssignedCostCentersError(input.nodeId));
  }

  // Delete the node
  await db.deleteFrom("CostCenterHierarchyNode").where("id", "=", input.nodeId).execute();

  return ok({ nodeId: input.nodeId });
}
