# Redirect all traffic from www.nkode.tech to nkode.tech
server {
    listen 80;
    server_name www.nkode.tech;

    return 301 https://nkode.tech$request_uri;
}

# Redirect HTTP to HTTPS for nkode.tech
server {
    listen 80;
    server_name nkode.tech;

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

# Main server block for nkode.tech with SSL and content configuration
server {
    listen 443 ssl http2;
    server_name nkode.tech;

    ssl_certificate /etc/letsencrypt/live/nkode.tech/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/nkode.tech/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/nkode.tech/chain.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/ssl/certs/dhparam.pem;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;

    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options DENY;
    add_header Referrer-Policy "no-referrer-when-downgrade";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    root /var/www/webapp;
    index index.html;

    # Routing for Flutter SPA
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Caching for Static Assets
    location ~* \.(?:js|css|png|jpg|jpeg|gif|svg|ico|woff2?)$ {
        expires 1y;
        add_header Cache-Control "public, max-age=31536000, immutable";
    }

    # Error pages
    error_page 404 /404.html;
    location = /404.html {
        root /var/www/webapp;
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /var/www/webapp;
    }

    # Optional: Enable Gzip Compression
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_min_length 256;
}
