<?php

namespace App\Shared\DependencyInjection;

use Symfony\Component\DependencyInjection\EnvVarProcessorInterface;

/**
 * Builds the nelmio CORS origin regex from a comma-separated host list
 * (ALLOWED_FRONTEND_HOSTS). That env is Coolify-safe (no `$` / `\`), whereas a
 * ready-made regex env is mangled by Coolify's variable interpolation and reaches
 * the container broken — so we assemble the regex in PHP instead.
 *
 * Usage: %env(cors_regex:ALLOWED_FRONTEND_HOSTS)%
 */
final class CorsRegexEnvProcessor implements EnvVarProcessorInterface
{
    public function getEnv(string $prefix, string $name, \Closure $getEnv): string
    {
        $raw   = (string) $getEnv($name);
        $hosts = array_values(array_filter(array_map('trim', explode(',', $raw))));

        if ($hosts === []) {
            // Match nothing rather than emit an empty (accept-all/reject-all-ambiguous) pattern.
            return '(?!)';
        }

        $alts = implode('|', array_map(
            static fn (string $h): string => preg_quote($h, '#'),
            $hosts
        ));

        // Same shape as the previous CORS_ALLOW_ORIGIN: optional subdomain, http or
        // https (dev localhost uses http), optional port, anchored.
        return '^https?://([a-z0-9-]+\.)*(' . $alts . ')(:[0-9]+)?$';
    }

    public static function getProvidedTypes(): array
    {
        return ['cors_regex' => 'string'];
    }
}
