apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: mailu-ingress
  namespace: bakery-ia
  labels:
    app.kubernetes.io/name: mailu
    app.kubernetes.io/component: ingress
    environment: production
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-production
    # Proxy settings for large attachments and long connections
    nginx.ingress.kubernetes.io/proxy-body-size: "100m"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
    nginx.ingress.kubernetes.io/proxy-connect-timeout: "60"
    # SSL redirect
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    # CRITICAL: Disable proxy buffering for webmail streaming/long-polling
    # This prevents the "stuck loading" issue with Roundcube webmail
    # Reference: https://github.com/Mailu/Mailu/issues/2850
    nginx.ingress.kubernetes.io/proxy-buffering: "off"
    nginx.ingress.kubernetes.io/proxy-request-buffering: "off"
    # WebSocket support for webmail real-time features
    nginx.ingress.kubernetes.io/proxy-http-version: "1.1"
    nginx.ingress.kubernetes.io/upstream-hash-by: "$remote_addr"
    # CRITICAL: Configuration snippet for Mailu header handling
    # Fixes redirect loops by ensuring Mailu sees the correct protocol
    # Reference: https://mailu.io/2.0/reverse.html
    nginx.ingress.kubernetes.io/configuration-snippet: |
      # CRITICAL: Force X-Forwarded-Proto to https to prevent redirect loops
      # Mailu's internal nginx checks this header to decide if redirect is needed
      proxy_set_header X-Forwarded-Proto https;
      proxy_set_header X-Forwarded-Port 443;
      proxy_set_header X-Forwarded-Ssl on;

      # Real IP headers for Mailu logging and rate limiting
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

      # Fix redirects from Mailu internal services (admin, webmail)
      # Don't add trailing slash to prevent 404 on redirects
      proxy_redirect http://localhost https://$host;
      proxy_redirect https://localhost https://$host;
      proxy_redirect http://$host https://$host;

      # Disable buffering for streaming responses (webmail)
      proxy_buffering off;
      proxy_cache off;
spec:
  ingressClassName: nginx
  tls:
  - hosts:
    - mail.bakewise.ai
    secretName: bakery-ia-prod-tls-cert
  rules:
  - host: mail.bakewise.ai
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: mailu-front
            port:
              number: 80
