package cybersecurity

import (
	"encoding/binary"
	"fmt"
	"net"
)

// ParseIPCIDR parsea una notacion CIDR y devuelve la direccion de red, broadcast, cantidad de hosts y error.
func ParseIPCIDR(cidr string) (network string, broadcast string, hosts int, err error) {
	ip, ipNet, err := net.ParseCIDR(cidr)
	if err != nil {
		return "", "", 0, fmt.Errorf("CIDR invalido: %w", err)
	}

	// Solo soportamos IPv4
	ip4 := ip.To4()
	if ip4 == nil {
		return "", "", 0, fmt.Errorf("solo se soporta IPv4")
	}

	mask := ipNet.Mask
	networkIP := ipNet.IP.To4()
	network = networkIP.String()

	// Calcular broadcast
	broadcastIP := make(net.IP, 4)
	for i := 0; i < 4; i++ {
		broadcastIP[i] = networkIP[i] | ^mask[i]
	}
	broadcast = broadcastIP.String()

	// Calcular hosts usables
	netInt := binary.BigEndian.Uint32(networkIP)
	bcastInt := binary.BigEndian.Uint32(broadcastIP)
	total := int(bcastInt - netInt + 1)
	if total > 2 {
		hosts = total - 2 // excluir network y broadcast
	} else {
		hosts = total // /31 o /32
	}

	return network, broadcast, hosts, nil
}
