// Is the IPv4 `ipAddress` inside the CIDR `subnet` (e.g. "10.0.0.0/24")?

const ipv4ToInt = (ip: string): number | null => {
  const parts = ip.trim().split('.');
  if (parts.length !== 4) return null;
  let value = 0;
  for (const part of parts) {
    const octet = Number(part);
    if (!Number.isInteger(octet) || octet < 0 || octet > 255) return null;
    // Unsigned 32-bit accumulation.
    value = value * 256 + octet;
  }
  return value >>> 0;
};

export const isIpAddressInSubnet = (ipAddress: string, subnet: string): boolean => {
  const [subnetIp, prefixRaw] = subnet.split('/');
  const prefix = Number(prefixRaw);
  const ipInt = ipv4ToInt(ipAddress);
  const subnetInt = ipv4ToInt(subnetIp);
  if (ipInt === null || subnetInt === null || !Number.isInteger(prefix) || prefix < 0 || prefix > 32) {
    return false;
  }
  // /0 matches everything; avoid the undefined `<< 32` shift.
  const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;
  return (ipInt & mask) === (subnetInt & mask);
};
