server {
    listen 80;
    server_name localhost;
    root /usr/share/nginx/html;
    index index.html index.htm;

    # Logs
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Proxy para peticiones CalDAV/CardDAV hacia Radicale
    location ~ ^/(caldav\.php/|radicale/|\.well-known/) {
        rewrite ^/radicale/(.*)$ /$1 break;
        rewrite ^/caldav\.php/(.*)$ /$1 break;
        proxy_pass http://radicale:5232;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # Headers para CalDAV/CardDAV
        proxy_set_header Depth $http_depth;
        proxy_set_header Destination $http_destination;
        proxy_set_header Overwrite $http_overwrite;

        # CORS headers
        add_header Access-Control-Allow-Origin "*" always;
        add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, UNLOCK, REPORT" always;
        add_header Access-Control-Allow-Headers "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Authorization, Destination, Overwrite" always;
        add_header Access-Control-Expose-Headers "ETag" always;

        # Preflight requests
        if ($request_method = OPTIONS) {
            return 204;
        }
    }

    # Servir archivos estáticos de InfCloud
    location /infcloud/ {
        alias /usr/share/nginx/infcloud/;
        try_files $uri $uri/ =404;

        # No cache para desarrollo
        add_header Cache-Control "no-store, no-cache, must-revalidate";
        add_header Pragma "no-cache";
        expires -1;
    }

    # Servir InfCloud directamente en la raíz sin redirección
    location = / {
        alias /usr/share/nginx/infcloud/;
        try_files /index.html =404;
    }

    # Todo lo demás a InfCloud (excepto las rutas de proxy ya definidas)
    location / {
        try_files /infcloud$uri /infcloud$uri/ /infcloud/index.html =404;
    }

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
}