server {
    listen 80;
    listen [::]:80;
    server_name mcp.mozartdigital.docker;

    # Redirection HTTP vers HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    # Configuration SSL
    ssl_certificate /usr/local/share/ca-certificates/mcp.mozartdigital.docker.crt;
    ssl_certificate_key /usr/local/share/ca-certificates/mcp.mozartdigital.docker.key;

    # Paramètres SSL sécurisés
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    server_name mcp.mozartdigital.docker;
    root /var/www/html/apps/apis/mcp/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    # Configuration spéciale pour l'endpoint SSE - DOIT être avant la location générale PHP
    location /mcp/sse {
        try_files $uri /index.php?$query_string;

        fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;

        # Timeouts pour SSE - connexions long-polling
        fastcgi_read_timeout 3600s;
        fastcgi_send_timeout 3600s;

        # Headers pour SSE
        fastcgi_buffering off;
        fastcgi_request_buffering off;

        # Headers SSE spécifiques
        add_header Cache-Control "no-cache";
        add_header Connection "keep-alive";
        add_header Access-Control-Allow-Origin "*";
        add_header Access-Control-Allow-Headers "Cache-Control";

        # Force le flush des données
        gzip off;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}