package cybersecurity

import (
	"fmt"
	"io"
	"net"
	"strings"
	"time"
)

// LookupWhois realiza una consulta WHOIS para el dominio proporcionado conectandose al servidor whois.iana.org.
func LookupWhois(domain string) (string, error) {
	conn, err := net.DialTimeout("tcp", "whois.iana.org:43", 10*time.Second)
	if err != nil {
		return "", fmt.Errorf("error conectando al servidor WHOIS: %w", err)
	}
	defer conn.Close()

	_ = conn.SetDeadline(time.Now().Add(10 * time.Second))

	_, err = fmt.Fprintf(conn, "%s\r\n", domain)
	if err != nil {
		return "", fmt.Errorf("error enviando consulta WHOIS: %w", err)
	}

	var sb strings.Builder
	_, err = io.Copy(&sb, conn)
	if err != nil {
		return "", fmt.Errorf("error leyendo respuesta WHOIS: %w", err)
	}

	return sb.String(), nil
}
