<?php
namespace EasyChat\Library\Email;

 
final class EmailEndpoint {
    public static function normalizeHost(string $host, bool $allow_private = false): string {
        $host = strtolower(rtrim(trim($host), '.'));
        if ($host === '' || strlen($host) > 253 || strpos($host, '://') !== false || preg_match('/[\s\/@?#]/', $host)) return '';
        if (filter_var($host, FILTER_VALIDATE_IP)) return self::publicIp($host) || $allow_private ? $host : '';
        if (!preg_match('/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/', $host)) return '';
        $records = @dns_get_record($host, DNS_A | DNS_AAAA);
        if (!$records) return '';
        foreach ($records as $record) {
            $ip = (string)($record['ip'] ?? ($record['ipv6'] ?? ''));
            if ($ip !== '' && !self::publicIp($ip) && !$allow_private) return '';
        }
        return $host;
    }

    public static function normalizePort($port, string $kind): int {
        $port = (int)$port;
        $allowed = $kind === 'imap' ? [993] : [465, 587];
        return in_array($port, $allowed, true) ? $port : 0;
    }

     
    public static function resolveAddress(string $host, bool $allow_private = false): string {
        $host=self::normalizeHost($host,$allow_private);if($host==='')return '';
        if(filter_var($host,FILTER_VALIDATE_IP))return $host;
        $records=@dns_get_record($host,DNS_A|DNS_AAAA);foreach((array)$records as $record){$ip=(string)($record['ip']??($record['ipv6']??''));if($ip!==''&&(self::publicIp($ip)||$allow_private))return $ip;}return '';
    }

    public static function socketHost(string $ip): string { return strpos($ip,':')!==false?'['.$ip.']':$ip; }

    private static function publicIp(string $ip): bool {
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
    }
}
