#!/bin/bash
# shellcheck shell=bash
#
# Fragmento compartido: equivalente Apache de `frontend/nginx.conf.PROD`
# - Backend:  http://127.0.0.1:3000
# - Frontend: http://127.0.0.1:8080
#
# Requiere (antes de source):
#   - SUDO ("" si eres root; "sudo" si no)
#   - PROJECT_NAME (opcional)
#   - APACHE_SITES (opcional; por defecto /etc/apache2/sites-available)

: "${SUDO:=sudo}"
: "${PROJECT_NAME:=englishworldcenter-chatbot}"
: "${APACHE_SITES:=/etc/apache2/sites-available}"

write_apache_ewc_proxy_conf() {
    $SUDO tee "${APACHE_SITES}/${PROJECT_NAME}-proxy.conf" > /dev/null <<'EWC_PROXY_EOF'
# Reverse proxy EWC Chatbot — alineado con frontend/nginx.conf.PROD
# Backend :3000 | Frontend (nginx en Docker) :8080

# Equivalente a: client_max_body_size 5m;
LimitRequestBody 5242880

ProxyRequests Off
ProxyPreserveHost On

# Orden: rutas más específicas antes que /
ProxyPass        /api/       http://127.0.0.1:3000/api/       retry=0 timeout=300
ProxyPassReverse /api/       http://127.0.0.1:3000/api/

ProxyPass        /uploads/   http://127.0.0.1:3000/uploads/   retry=0 timeout=300
ProxyPassReverse /uploads/   http://127.0.0.1:3000/uploads/

ProxyPass        /health     http://127.0.0.1:3000/health     retry=0 timeout=60
ProxyPassReverse /health     http://127.0.0.1:3000/health

# WebSocket (/ws)
ProxyPass        /ws         ws://127.0.0.1:3000/ws           retry=0 upgrade=websocket timeout=86400
ProxyPassReverse /ws         ws://127.0.0.1:3000/ws

ProxyPass        /           http://127.0.0.1:8080/           retry=0 timeout=60
ProxyPassReverse /           http://127.0.0.1:8080/

# Cabeceras de seguridad (paridad con nginx.conf.PROD)
# En Nginx se usa: proxy_hide_header Content-Security-Policy;
# En Apache quitamos CSP previa y fijamos la nuestra.
Header unset Content-Security-Policy
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "no-referrer-when-downgrade"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
Header always set Content-Security-Policy "default-src 'self' http: https: data: blob; connect-src 'self' http: https: ws: wss: https://api.elevenlabs.io wss://api.elevenlabs.io; img-src 'self' data: https:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com blob: data:; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.googleapis.com; font-src 'self' data: https: https://fonts.gstatic.com https://cdnjs.cloudflare.com; media-src 'self' blob: data: https:"
EWC_PROXY_EOF
}

write_apache_ewc_ssl_vhost() {
    local domain="$1"

    # mod_http2 + Protocols h2 no es compatible con mpm_prefork (común con mod_php)
    local protocols_line
    if $SUDO apache2ctl -V 2>/dev/null | grep -qi 'prefork' || $SUDO apachectl -V 2>/dev/null | grep -qi 'prefork'; then
        protocols_line="    # HTTP/2 omitido (MPM prefork). Para habilitarlo: a2dismod mpm_prefork && a2enmod mpm_event && a2enmod http2"
    else
        $SUDO a2enmod http2 2>/dev/null || true
        protocols_line="    Protocols h2 http/1.1"
    fi

    $SUDO tee "${APACHE_SITES}/${PROJECT_NAME}-le-ssl.conf" > /dev/null <<EOF
<VirtualHost *:443>
    ServerName ${domain}
#    ServerTokens Prod
${protocols_line}

    SSLEngine on
    SSLCertificateFile      /etc/letsencrypt/live/${domain}/fullchain.pem
    SSLCertificateKeyFile   /etc/letsencrypt/live/${domain}/privkey.pem

    <IfFile /etc/letsencrypt/options-ssl-apache.conf>
        Include /etc/letsencrypt/options-ssl-apache.conf
    </IfFile>
    <IfFile /etc/letsencrypt/ssl-dhparams.pem>
        SSLOpenSSLConfCmd DHParameters "/etc/letsencrypt/ssl-dhparams.pem"
    </IfFile>

    Include ${APACHE_SITES}/${PROJECT_NAME}-proxy.conf
</VirtualHost>
EOF
}
