<?php
declare(strict_types=1);

namespace App\Middleware;

use App\Core\Request;
use App\Core\Response;
use App\Core\App;

final class CorsMiddleware
{
    public function handle(Request $request, callable $next): Response
    {
        $config = App::getInstance()->config('api.cors', []);
        $origin = $request->header('Origin') ?? '';

        $allowedOrigins = $config['allowed_origins'] ?? [];
        $allowOrigin = in_array($origin, $allowedOrigins, true) ? $origin : '';

        if ($request->method() === 'OPTIONS') {
            $response = new Response();
            return $response->json(null, 204)
                ->header('Access-Control-Allow-Origin', $allowOrigin)
                ->header('Access-Control-Allow-Methods', implode(', ', $config['allowed_methods'] ?? []))
                ->header('Access-Control-Allow-Headers', implode(', ', $config['allowed_headers'] ?? []))
                ->header('Access-Control-Max-Age', (string) ($config['max_age'] ?? 86400))
                ->header('Access-Control-Allow-Credentials', ($config['allow_credentials'] ?? false) ? 'true' : 'false');
        }

        $response = $next($request);

        if ($allowOrigin !== '') {
            $response->header('Access-Control-Allow-Origin', $allowOrigin);
            $response->header('Access-Control-Allow-Credentials', ($config['allow_credentials'] ?? false) ? 'true' : 'false');
            $response->header('Access-Control-Expose-Headers', implode(', ', $config['exposed_headers'] ?? []));
        }

        return $response;
    }
}
