{{/*
ConfigMap containing the nginx configuration
Enables serving status.json via GET and updating via POST requests
*/}}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "gitops-status-server.fullname" . }}-nginx-config
  labels:
    {{- include "gitops-status-server.labels" . | nindent 4 }}
data:
  nginx.conf: |
    # Minimal nginx config for serving and updating status.json
    user nginx;
    worker_processes auto;
    error_log /var/log/nginx/error.log warn;
    pid /var/run/nginx.pid;

    events {
      worker_connections 1024;
    }

    http {
      include /etc/nginx/mime.types;
      default_type application/octet-stream;

      log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

      access_log /var/log/nginx/access.log main;

      sendfile on;
      tcp_nopush on;
      tcp_nodelay on;
      keepalive_timeout 65;
      types_hash_max_size 2048;
      client_max_body_size 1M;

      # Gzip compression
      gzip on;
      gzip_vary on;
      gzip_types text/plain text/css text/xml text/javascript 
                 application/x-javascript application/xml+rss 
                 application/json;

      upstream api_backend {
        server 127.0.0.1:5000;
        keepalive 32;
      }

      server {
        listen 8080 default_server;
        server_name _;

        # Serve status.json as read-only
        location /status.json {
          alias /usr/share/nginx/html/status.json;
          add_header Cache-Control "no-cache, no-store, must-revalidate";
          add_header Pragma "no-cache";
          add_header Expires "0";
        }

        # Health check endpoint
        location /health {
          access_log off;
          return 200 "healthy\n";
          add_header Content-Type text/plain;
        }

        # Proxy POST requests to the API backend (Python Flask)
        location /api/ {
          proxy_pass http://api_backend;
          proxy_http_version 1.1;
          proxy_set_header Connection "";
          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 $scheme;
          
          # Buffer settings for POST requests
          proxy_request_buffering off;
          proxy_buffering off;
          
          # Timeouts
          proxy_connect_timeout 30s;
          proxy_send_timeout 30s;
          proxy_read_timeout 30s;
        }

        # Catch-all for root
        location / {
          return 301 /status.json;
        }
      }
    }
