package me.qwq.doghouse.pojo.bo;
import java.math.BigInteger;
import java.net.InetAddress;

/**
 * CIDR IP 段
 */
public class CidrBlock {

    private final BigInteger networkAddress;
    private final BigInteger mask;

    public CidrBlock(String cidr) {
        try {
            String[] parts = cidr.split("/");
            String addr = parts[0];
            int prefix = Integer.parseInt(parts[1]);

            InetAddress inetAddress = InetAddress.getByName(addr);
            byte[] addressBytes = inetAddress.getAddress();
            int maxPrefix = addressBytes.length * 8;

            if (prefix < 0 || prefix > maxPrefix) {
                throw new IllegalArgumentException("Invalid prefix length: " + cidr);
            }

            BigInteger ipVal = new BigInteger(1, addressBytes);
            BigInteger maskVal = BigInteger.ONE.shiftLeft(maxPrefix).subtract(BigInteger.ONE)
                    .shiftLeft(maxPrefix - prefix);

            this.networkAddress = ipVal.and(maskVal);
            this.mask = maskVal;
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid CIDR: " + cidr, e);
        }
    }

    public boolean contains(String ip) {
        try {
            InetAddress addr = InetAddress.getByName(ip);
            BigInteger ipVal = new BigInteger(1, addr.getAddress());
            return ipVal.and(mask).equals(networkAddress);
        } catch (Exception e) {
            return false;
        }
    }
}