<?php

declare(strict_types=1);

namespace App\Core;

final class UrlHelper
{
    public static function publicBaseUrl(): string
    {
        $base = Env::get('PUBLIC_BASE_URL') ?: Env::get('APP_URL') ?: self::detectBaseUrl();
        return rtrim((string) $base, '/');
    }

    public static function detectBaseUrl(): string
    {
        $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['SERVER_PORT'] ?? '') === '443');
        $scheme = $https ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? '127.0.0.1:8081';
        return $scheme . '://' . $host;
    }

    public static function normalizeAssetUrl(?string $url): ?string
    {
        if ($url === null) return null;
        $url = trim($url);
        if ($url === '') return null;
        if (str_starts_with($url, 'data:') || str_starts_with($url, 'blob:')) return $url;

        $base = self::publicBaseUrl();

        $url = preg_replace('/([?&])(v|t|cache)=\d+(&)?/i', '$1', $url) ?? $url;
        $url = rtrim($url, '?&');

        // Corrige URLs antigas geradas por ambientes diferentes.
        $url = preg_replace('#^https?://127\.0\.0\.1:8000#', $base, $url) ?? $url;
        $url = preg_replace('#^https?://127\.0\.0\.1:8081#', $base, $url) ?? $url;
        $url = preg_replace('#^https?://localhost:8000#', $base, $url) ?? $url;
        $url = preg_replace('#^https?://localhost:8081#', $base, $url) ?? $url;
        $url = preg_replace('#^https?://api-reurbtec\.sisprom\.com\.br#', $base, $url) ?? $url;

        if (preg_match('#^https?://#i', $url)) {
            $path = parse_url($url, PHP_URL_PATH) ?: '';
            if (str_starts_with($path, '/api/v1/storage/public/')) {
                return $base . $path;
            }
            return $url;
        }

        $clean = ltrim(str_replace('\\', '/', $url), '/');

        if (str_starts_with($clean, 'api/v1/storage/public/')) {
            return $base . '/' . $clean;
        }

        if (str_starts_with($clean, 'storage/uploads/')) {
            $clean = substr($clean, strlen('storage/uploads/'));
        }

        if (str_starts_with($clean, 'branding-assets/')) {
            $clean = 'uploads/identidade_visual/' . substr($clean, strlen('branding-assets/'));
        }
        if (str_starts_with($clean, 'identidade_visual/')) {
            $clean = 'uploads/' . $clean;
        }

        if (str_starts_with($clean, 'uploads/identidade_visual/')) {
            // Asset público espelhado em public/uploads/identidade_visual.
            // Isso permite abrir a imagem mesmo quando o servidor PHP embutido roda sem router.php.
            return $base . '/' . $clean;
        }

        return $url;
    }
}
