import { canAllocateOnNode, evaluateNodeCapacity } from './capacity';
import type { NodeSnapshot } from './types';

export function selectNodeForAllocation(
  nodes: NodeSnapshot[],
  requiredRamMb: number,
): NodeSnapshot | null {
  const candidates = nodes
    .filter((node) => canAllocateOnNode(node, requiredRamMb))
    .map((node) => ({
      node,
      capacity: evaluateNodeCapacity(node, requiredRamMb),
    }))
    .sort((left, right) => {
      if (right.capacity.score !== left.capacity.score) {
        return right.capacity.score - left.capacity.score;
      }

      return left.node.reservedRamMb - right.node.reservedRamMb;
    });

  return candidates[0]?.node ?? null;
}

export function findNodeSnapshot(
  nodes: NodeSnapshot[],
  nodeId: string,
): NodeSnapshot | null {
  return nodes.find((node) => node.id === nodeId) ?? null;
}
