upstream frontend {
    server web:4002;
}

upstream api_backend {
    server api:4003;
}

upstream ws_backend {
    server ws:4004;
}

# Загальні CORS-заголовки
map $request_method $cors_preflight {
    OPTIONS 1;
    default 0;
}

server {
    listen 80;
    listen [::]:80;

    server_name ${DOMAIN} www.${DOMAIN};

    error_log  /var/log/nginx/sheep-service.error.log error;
    access_log /var/log/nginx/sheep-service.access.log;

    root /usr/share/nginx/html/sheep-service.com;
    index index.html;
    error_page 404 /404.html;

    # Захист службових файлів
    location ~ /\.(git|env) {
        deny all;
    }

    # API
    location /api/ {
        proxy_pass http://api_backend$request_uri;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    # WebSocket
    location /ws {
        proxy_pass http://ws_backend$request_uri;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    # Frontend
    location / {
        proxy_pass http://frontend$request_uri;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}