<VirtualHost *:80>
    ServerName luckyst.trade
    ServerAlias www.luckyst.trade

    # ==========================================================
    # Frontend: Serve static React build
    # ==========================================================
    DocumentRoot /var/www/luckyst.trade

    <Directory /var/www/luckyst.trade>
        Options -Indexes +FollowSymLinks
        AllowOverride None
        Require all granted

        # SPA fallback: serve index.html for client-side routes
        RewriteEngine On
        RewriteBase /
        RewriteRule ^index\.html$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_URI} !^/api
        RewriteCond %{REQUEST_URI} !^/ws
        RewriteCond %{REQUEST_URI} !^/health
        RewriteRule . /index.html [L]
    </Directory>

    # ==========================================================
    # WebSocket: Proxy /ws/* to FastAPI (before API rules)
    # ==========================================================
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} websocket [NC]
    RewriteCond %{HTTP:Connection} upgrade [NC]
    RewriteRule ^/ws/(.*) ws://127.0.0.1:8000/ws/$1 [P,L]

    ProxyPass /ws/ ws://127.0.0.1:8000/ws/
    ProxyPassReverse /ws/ ws://127.0.0.1:8000/ws/

    # ==========================================================
    # Auth API: /api/auth/* -> backend /api/auth/* (no rewrite)
    # Auth router mounts at /api/auth in main.py
    # ==========================================================
    ProxyPass /api/auth/ http://127.0.0.1:8000/api/auth/
    ProxyPassReverse /api/auth/ http://127.0.0.1:8000/api/auth/

    # ==========================================================
    # Other API: /api/* -> backend /api/v1/*
    # Replicates Vite dev proxy rewrite (/api -> /api/v1)
    # ==========================================================
    ProxyPass /api/ http://127.0.0.1:8000/api/v1/
    ProxyPassReverse /api/ http://127.0.0.1:8000/api/v1/

    # ==========================================================
    # Health check passthrough
    # ==========================================================
    ProxyPass /health http://127.0.0.1:8000/health
    ProxyPassReverse /health http://127.0.0.1:8000/health

    # ==========================================================
    # Headers: Cloudflare Tunnel handles SSL termination
    # ==========================================================
    RequestHeader set X-Forwarded-Proto "https"
    RequestHeader set X-Forwarded-For "%{REMOTE_ADDR}s"

    # Logging
    ErrorLog ${APACHE_LOG_DIR}/luckyst-error.log
    CustomLog ${APACHE_LOG_DIR}/luckyst-access.log combined
</VirtualHost>
