import http from 'node:http';
import https from 'node:https';
import { lookup as dnsLookup } from 'node:dns';
import { BlockList, isIP } from 'node:net';

/**
 * Outbound calls to an address a tenant typed in (the BMS pull connector):
 * only to the public internet. The address is checked where it is resolved
 * for the connection itself, so a name cannot pass the check and then point
 * somewhere private (DNS rebinding); IPv4 written as IPv6 is unwrapped; no
 * redirects are followed; the answer is size-capped; errors say what went
 * wrong without echoing what came back.
 */

const blocked = new BlockList();
for (const [net, bits] of [
  ['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12],
  ['192.0.0.0', 24], ['192.0.2.0', 24], ['192.88.99.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['198.51.100.0', 24],
  ['203.0.113.0', 24], ['224.0.0.0', 4], ['240.0.0.0', 4],
] as const) blocked.addSubnet(net, bits, 'ipv4');
for (const [net, bits] of [
  ['::', 128], ['::1', 128], ['64:ff9b::', 96], ['64:ff9b:1::', 48], ['100::', 64], ['2001::', 32], ['2001:db8::', 32], ['2002::', 16], ['fc00::', 7], ['fe80::', 10], ['ff00::', 8],
] as const) blocked.addSubnet(net, bits, 'ipv6');

/** IPv4 hidden in IPv6 (::ffff:7f00:1, ::ffff:127.0.0.1, ::127.0.0.1), unwrapped. */
function unwrap(ip: string): { ip: string; family: 'ipv4' | 'ipv6' } {
  const v = ip.toLowerCase().replace(/^\[|\]$/g, '');
  if (isIP(v) === 4) return { ip: v, family: 'ipv4' };
  const m = v.match(/^(?:0*:)*(?:ffff:)?(\d+\.\d+\.\d+\.\d+)$/) ?? v.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
  if (m && m.length === 2) return { ip: m[1], family: 'ipv4' };
  if (m && m.length === 3) {
    const hi = parseInt(m[1], 16);
    const lo = parseInt(m[2], 16);
    return { ip: `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`, family: 'ipv4' };
  }
  return { ip: v, family: 'ipv6' };
}

export function isPublicAddress(ip: string) {
  const u = unwrap(ip);
  if (!isIP(u.ip)) return false;
  return !blocked.check(u.ip, u.family);
}

/** Private addresses are allowed only while developing or testing (the BMS simulator). */
export const relaxedOutbound = () => process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test';

export class OutboundError extends Error {}

/** GET a JSON document from a public https address (http and private ones too while developing). */
export async function getPublicJson(url: URL, opts: { headers?: Record<string, string>; timeoutMs?: number; maxBytes?: number } = {}): Promise<unknown> {
  const relaxed = relaxedOutbound();
  if (url.protocol !== 'https:' && !(relaxed && url.protocol === 'http:')) throw new OutboundError('The address must start with https://');
  const host = url.hostname.replace(/^\[|\]$/g, '');
  if (!relaxed && (host === 'localhost' || (isIP(host) && !isPublicAddress(host)))) throw new OutboundError('The address must be on the public internet');
  const maxBytes = opts.maxBytes ?? 5 * 1024 * 1024;
  const lookup: typeof dnsLookup = ((hostname: string, options: object, cb: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => {
    dnsLookup(hostname, { all: true }, (err, addresses) => {
      if (err) return cb(err, '', 0);
      const list = addresses as { address: string; family: number }[];
      if (!list.length) return cb(new OutboundError('That address does not resolve'), '', 0);
      if (!relaxed && list.some((a) => !isPublicAddress(a.address))) return cb(new OutboundError('The address must be on the public internet'), '', 0);
      const all = (options as { all?: boolean }).all;
      if (all) return (cb as unknown as (e: null, a: typeof list) => void)(null, list);
      cb(null, list[0].address, list[0].family);
    });
  }) as unknown as typeof dnsLookup;
  const client = url.protocol === 'https:' ? https : http;
  return new Promise((resolve, reject) => {
    const req = client.get(url, { headers: { Accept: 'application/json', ...opts.headers }, lookup, timeout: opts.timeoutMs ?? 20_000 }, (res) => {
      if (res.statusCode !== 200) {
        res.resume();
        return reject(new OutboundError(`The server answered ${res.statusCode ?? 'nothing'}`));
      }
      let size = 0;
      const chunks: Buffer[] = [];
      res.on('data', (c: Buffer) => {
        size += c.length;
        if (size > maxBytes) {
          req.destroy();
          reject(new OutboundError('The answer is too large'));
        } else chunks.push(c);
      });
      res.on('end', () => {
        try {
          resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
        } catch {
          reject(new OutboundError('The answer is not JSON'));
        }
      });
      res.on('error', () => reject(new OutboundError('The connection broke')));
    });
    req.on('timeout', () => req.destroy(new OutboundError('The server took too long')));
    req.on('error', (e) => reject(e instanceof OutboundError ? e : new OutboundError('Could not reach the server')));
  });
}
