<?php

namespace App\Support;

use App\Models\Router;
use Illuminate\Support\Facades\Cache;

class RouterHost
{
    public static function resolve(Router $r): string
    {
        // Future: if using VPN
        if (($r->connection_via === 'vpn' || $r->prefer_vpn) && $r->vpn_ip) {
            return $r->vpn_ip;
        }

        // Public path: prefer DDNS when provided, else WAN IP
        $host = $r->ddns_host ?: $r->wan_host ?: $r->host;

        // If host looks like a hostname, resolve and cache it for 60s to avoid DNS spikes
        if ($host && preg_match('/[a-zA-Z]/', $host)) {
            return Cache::remember("router:resolv:{$r->id}", 60, function() use ($host){
                $ip = gethostbyname($host);
                return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : $host; // fallback to original
            });
        }
        return $host;
    }
}
