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

export interface DeleteProfitCenterHierarchyNodeInput {
  nodeId: string;
}

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

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

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

  // Check for child nodes
  const childNode = await db
    .selectFrom("ProfitCenterHierarchyNode")
    .selectAll()
    .where("parentNodeId", "=", input.nodeId)
    .executeTakeFirst();

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

  // Check for assigned profit centers
  const assignedProfitCenter = await db
    .selectFrom("ProfitCenterHierarchyAssignment")
    .selectAll()
    .where("hierarchyNodeId", "=", input.nodeId)
    .executeTakeFirst();

  if (assignedProfitCenter) {
    return err(new NodeHasAssignedProfitCentersError(input.nodeId));
  }

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

  return ok({ profitCenterHierarchyNode: node });
}
