events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # Map to determine which backend to use based on host
    map $http_host $backend_port {
        default 4000;
        ~^admin\. 4002;
    }

    server {
        listen 8080;
        server_name _;

        # Proxy to actual asciinema server (port depends on subdomain)
        location / {
            proxy_pass http://asciinema_backend:$backend_port;
            proxy_set_header Host $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;

            # Inject custom JavaScript into HTML responses
            sub_filter '</head>' '<script src="/theme/inject.js"></script></head>';
            sub_filter_once on;
            sub_filter_types text/html;
        }

        # Serve theme files directly
        location /theme/ {
            alias /theme/;
            expires 1d;
            add_header Cache-Control "public, immutable";
        }
    }
}
