<?php

$originFromUrl = static function (?string $url): ?string {
    if (! $url) {
        return null;
    }

    $parts = parse_url($url);
    if (! $parts || ! isset($parts['scheme'], $parts['host'])) {
        return null;
    }

    $origin = strtolower($parts['scheme'].'://'.$parts['host']);

    if (isset($parts['port'])) {
        $origin .= ':'.$parts['port'];
    }

    return $origin;
};

$envOrigins = array_filter(array_map('trim', explode(',', (string) env('CORS_ALLOWED_ORIGINS', ''))));
$appOrigin = $originFromUrl(env('APP_URL'));
$devOrigins = env('APP_ENV') === 'production'
    ? []
    : [
        'http://localhost:5173',
        'http://127.0.0.1:5173',
        'https://localhost:5173',
        'https://127.0.0.1:5173',
        'http://localhost:3000',
        'http://127.0.0.1:3000',
        'https://localhost:3000',
        'https://127.0.0.1:3000',
    ];

$allowedOrigins = array_values(array_unique(array_filter(array_merge(
    $envOrigins,
    [$appOrigin],
    $devOrigins
))));

$allowedMethods = array_filter(array_map('trim', explode(',', (string) env('CORS_ALLOWED_METHODS', 'GET,POST,PUT,PATCH,DELETE,OPTIONS'))));
$allowedHeaders = array_filter(array_map('trim', explode(',', (string) env('CORS_ALLOWED_HEADERS', 'Content-Type,Authorization,X-Requested-With,X-Locale,X-Device-Id'))));

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Configure cross-origin settings for API and sanctum routes. Origins are
    | env-driven to match the front-proxy allowlist (nginx/traefik).
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => $allowedMethods === [] ? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] : $allowedMethods,

    'allowed_origins' => $allowedOrigins === [] ? ['http://localhost', 'http://127.0.0.1'] : $allowedOrigins,

    'allowed_origins_patterns' => [],

    'allowed_headers' => $allowedHeaders === [] ? ['Content-Type', 'Authorization', 'X-Requested-With'] : $allowedHeaders,

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => (bool) env('CORS_SUPPORTS_CREDENTIALS', false),

];
