# Upstream configuration for web and longpolling requests
upstream odoo-web {
    server web:8069;
}

upstream odoo-im {
    server web:8072;
}

# Redirect HTTP to HTTPS
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name .dine360.com;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

# HTTPS Server (SaaS wildcard routing)
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ~^(?<tenant>.+)\.dine360\.com$;

    # Wildcard SSL Certificates (managed via Let's Encrypt Certbot)
    ssl_certificate /etc/letsencrypt/live/dine360.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/dine360.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # Logger configurations
    access_log /var/log/nginx/odoo.access.log;
    error_log /var/log/nginx/odoo.error.log;

    # Buffer & Timeout settings for file uploads
    client_max_body_size 128M;
    keepalive_timeout 90;
    proxy_read_timeout 720s;
    proxy_connect_timeout 720s;
    proxy_send_timeout 720s;

    # Gzip Compression
    gzip on;
    gzip_types text/css text/scss text/plain text/xml application/xml application/json application/javascript;

    # Redirect longpolling chat/POS requests
    location /longpolling {
        proxy_pass http://odoo-im;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        proxy_redirect off;

        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 https;
    }

    # Standard Web requests proxy
    location / {
        proxy_pass http://odoo-web;
        proxy_redirect off;

        # Core headers for multi-tenant database filtering
        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 https;
        proxy_set_header X-Forwarded-Host $host;
        
        # Enables Odoo dbfilter configuration matching
        # Converts tenant.dine360.com requests into filtering by 'dine360_restaurant_tenant' database
        proxy_set_header X-Odoo-dbfilter dine360_restaurant_$tenant;

        # Mitigate HTTPoxy vulnerability
        proxy_set_header Proxy "";
    }

    # Static resources cache
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff|woff2|svg)$ {
        proxy_cache_valid 200 60m;
        proxy_pass http://odoo-web;
        expires 7d;
    }
}
