<?php

declare(strict_types=1);

namespace App\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Psr7\Response;

class CorsMiddleware
{
    private array $allowedOrigins;

    public function __construct()
    {
        $origins = $_ENV['CORS_ORIGINS'] ?? 'https://chrono.mykollector.com,https://fab.mykollector.com,https://pwa.mykollector.com,https://workflow.mykollector.com';
        $this->allowedOrigins = array_map('trim', explode(',', $origins));
        // Toujours inclure pwa.mykollector.com même si absent du .env
        if (!in_array('https://pwa.mykollector.com', $this->allowedOrigins, true)) {
            $this->allowedOrigins[] = 'https://pwa.mykollector.com';
        }
    }

    public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $origin = $request->getHeaderLine('Origin');

        // Preflight OPTIONS
        if ($request->getMethod() === 'OPTIONS') {
            $response = new Response();
            return $this->addCorsHeaders($response, $origin)->withStatus(200);
        }

        $response = $handler->handle($request);
        return $this->addCorsHeaders($response, $origin);
    }

    private function addCorsHeaders(ResponseInterface $response, string $origin): ResponseInterface
    {
        if (in_array($origin, $this->allowedOrigins, true)) {
            $response = $response
                ->withHeader('Access-Control-Allow-Origin', $origin)
                ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
                ->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Agent-Key')
                ->withHeader('Access-Control-Allow-Credentials', 'true')
                ->withHeader('Access-Control-Max-Age', '86400');
        }
        return $response;
    }
}
