<?php

namespace App\Http\Concerns;

use Illuminate\Http\Request;

/**
 * Resolves the public base URL for agent install commands.
 *
 * Priority:
 *   1) APP_URL from .env (config/app.php), if set and not the default localhost
 *   2) Auto-detect from the incoming request — scheme + host + (port if non-default)
 *   3) Final fallback: 'http://localhost'
 *
 * Why auto-detect: when the operator deploys this dashboard at a new domain
 * but forgets to update APP_URL, install commands would point at the wrong
 * place. Worse, generated `curl ... localhost/install.sh` would silently fail
 * on the remote server. Reading the request's own host is what an admin would
 * paste into a browser — by definition the right URL.
 */
trait DerivesInstallBaseUrl
{
    /**
     * @return string  e.g. "https://noc.hostseba.com" (no trailing slash)
     */
    protected function installBaseUrl(Request $request): string
    {
        $configured = rtrim((string) config('app.url'), '/');

        // Treat ANY localhost-pointed APP_URL as "not configured" — including
        // values with a port like "http://localhost:8000" that the dev .env
        // ships with. If a real agent on a remote server fetches install
        // commands, baking in localhost is always wrong: use the hostname
        // the requester actually reached us at (ngrok / prod domain / LB).
        $isDefaulty = $configured === ''
            || preg_match('#^https?://localhost(:\d+)?$#i', $configured)
            || preg_match('#^https?://127\.0\.0\.1(:\d+)?$#i', $configured);

        if (!$isDefaulty) {
            return $configured;
        }

        // Fall back to the request's own scheme+host. APP_URL takes precedence
        // for production, but this lets a fresh install work out of the box —
        // the operator opens the dashboard in their browser, generates a
        // token, and the URL in the install command is always the URL they
        // just typed into the address bar.
        $scheme = $request->getScheme() ?: 'http';
        $host = $request->getHost();
        $port = $request->getPort();

        $standardPort = ($scheme === 'https' && $port == 443)
            || ($scheme === 'http' && $port == 80);

        return $standardPort
            ? "{$scheme}://{$host}"
            : "{$scheme}://{$host}:{$port}";
    }
}
