package com.xfestudio.xfeservermanager.infra.http;

import com.sun.net.httpserver.Headers;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/** Resolves X-Forwarded-For only when the TCP peer belongs to an explicit trusted CIDR. */
public final class TrustedProxyResolver {
    private static final int MAXIMUM_FORWARDERS = 16;
    private final List<Cidr> trustedCidrs;

    public TrustedProxyResolver(List<String> trustedProxyCidrs) {
        this.trustedCidrs = trustedProxyCidrs.stream().map(Cidr::parse).toList();
    }

    public String resolve(InetAddress peer, Headers headers) {
        if (!isTrusted(peer)) {
            return peer.getHostAddress();
        }
        String forwarded = headers.getFirst("X-Forwarded-For");
        if (forwarded == null || forwarded.isBlank()) {
            return peer.getHostAddress();
        }
        String[] entries = forwarded.split(",", MAXIMUM_FORWARDERS + 1);
        if (entries.length > MAXIMUM_FORWARDERS) {
            return peer.getHostAddress();
        }
        List<InetAddress> chain = new ArrayList<>(entries.length);
        for (String entry : entries) {
            InetAddress address = parseLiteral(entry.strip());
            if (address == null) {
                return peer.getHostAddress();
            }
            chain.add(address);
        }
        for (int index = chain.size() - 1; index >= 0; index--) {
            InetAddress candidate = chain.get(index);
            if (!isTrusted(candidate)) {
                return candidate.getHostAddress();
            }
        }
        return chain.isEmpty() ? peer.getHostAddress() : chain.get(0).getHostAddress();
    }

    private boolean isTrusted(InetAddress address) {
        return trustedCidrs.stream().anyMatch(cidr -> cidr.contains(address));
    }

    private static InetAddress parseLiteral(String value) {
        if (value.isEmpty() || value.length() > 45 || !value.matches("[0-9A-Fa-f:.]+")) {
            return null;
        }
        if (!value.contains(".") && !value.contains(":")) {
            return null;
        }
        if (!value.contains(":")) {
            String[] octets = value.split("\\.", -1);
            if (octets.length != 4) {
                return null;
            }
            for (String octet : octets) {
                try {
                    if (octet.isEmpty() || (octet.length() > 1 && octet.charAt(0) == '0')
                            || Integer.parseInt(octet) > 255) {
                        return null;
                    }
                } catch (NumberFormatException invalid) {
                    return null;
                }
            }
        }
        try {
            return InetAddress.getByName(value);
        } catch (UnknownHostException ignored) {
            return null;
        }
    }

    private record Cidr(byte[] network, int prefixLength) {
        private static Cidr parse(String value) {
            if (value == null || value.isBlank()) {
                throw new IllegalArgumentException("trusted proxy CIDR must not be blank");
            }
            String[] parts = value.strip().split("/", 2);
            InetAddress address = parseLiteral(parts[0]);
            if (address == null) {
                throw new IllegalArgumentException("invalid trusted proxy CIDR: " + value);
            }
            int maximum = address.getAddress().length * 8;
            int prefix;
            try {
                prefix = parts.length == 1 ? maximum : Integer.parseInt(parts[1]);
            } catch (NumberFormatException exception) {
                throw new IllegalArgumentException("invalid trusted proxy CIDR: " + value, exception);
            }
            if (prefix < 0 || prefix > maximum) {
                throw new IllegalArgumentException("invalid trusted proxy prefix: " + value);
            }
            byte[] network = address.getAddress().clone();
            mask(network, prefix);
            return new Cidr(network, prefix);
        }

        private boolean contains(InetAddress address) {
            byte[] candidate = address.getAddress().clone();
            if (candidate.length != network.length) {
                return false;
            }
            mask(candidate, prefixLength);
            return java.security.MessageDigest.isEqual(network, candidate);
        }

        private static void mask(byte[] bytes, int prefix) {
            int fullBytes = prefix / 8;
            int remaining = prefix % 8;
            if (remaining != 0 && fullBytes < bytes.length) {
                bytes[fullBytes] &= (byte) (0xff << (8 - remaining));
                fullBytes++;
            }
            java.util.Arrays.fill(bytes, fullBytes, bytes.length, (byte) 0);
        }
    }
}
