<IfModule mod_ssl.c>
    # 1) Apex-Domain (ypchat.net) liefert NUR Redirect auf www
    <VirtualHost *:443>
        ServerName ypchat.net

        Include /etc/letsencrypt/options-ssl-apache.conf
        SSLCertificateFile /etc/letsencrypt/live/ypchat.net/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/ypchat.net/privkey.pem

        RewriteEngine On
        RewriteRule ^ https://www.ypchat.net%{REQUEST_URI} [R=301,L]
    </VirtualHost>

    # 2) Canonical Host (www.ypchat.net) liefert die App
    <VirtualHost *:443>
        ServerName www.ypchat.net

        # SSL-Konfiguration
        Include /etc/letsencrypt/options-ssl-apache.conf
        SSLCertificateFile /etc/letsencrypt/live/ypchat.net/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/ypchat.net/privkey.pem

        # DocumentRoot (nur fuer statische Dateien wie ads.txt)
        DocumentRoot /opt/ypchat/docroot

        # Deaktiviere DirectoryIndex, damit Apache keine index.html direkt serviert.
        # Alle App-Anfragen sollen via Reverse-Proxy an Node.js gehen.
        DirectoryIndex disabled

        <Directory /opt/ypchat/docroot>
            AllowOverride None
            Require all granted
            Options -Indexes
        </Directory>

        # Spezielle Regel fuer /ads.txt (muss vor ProxyPass-Ausnahmen stehen)
        Alias /ads.txt /opt/ypchat/docroot/ads.txt
        <Location /ads.txt>
            Require all granted
        </Location>

        RewriteEngine On

        # Unerwuenschten Query-Parameter entfernen
        RewriteCond %{QUERY_STRING} ^(.*)&?wtd=UrId0B0tLmuMAK9H&?(.*)$ [NC]
        RewriteRule ^ %{REQUEST_URI}?%1%2 [R=301,L]

        # WebSocket-Support fuer Socket.IO (vor normalem ProxyPass)
        RewriteCond %{HTTP:Upgrade} websocket [NC]
        RewriteCond %{HTTP:Connection} upgrade [NC]
        RewriteRule ^/socket\.io/(.*) ws://localhost:4000/socket.io/$1 [P,L]

        ProxyPreserveHost On

        # Socket.IO (Polling + WS)
        ProxyPass /socket.io/ http://localhost:4000/socket.io/
        ProxyPassReverse /socket.io/ http://localhost:4000/socket.io/

        # Ausnahme fuer direkte statische Datei
        ProxyPass /ads.txt !

        # Alle anderen Requests an Node.js
        ProxyPass / http://localhost:4000/
        ProxyPassReverse / http://localhost:4000/

        ProxyRequests Off
        ProxyTimeout 300

        # Header fuer Backend / Express
        RequestHeader set X-Forwarded-Proto "https"
        RequestHeader set X-Forwarded-Port "443"
    </VirtualHost>
</IfModule>
