server {
    listen 80;
    server_name localhost;

    # Allow large client request bodies for file uploads in commits
    client_max_body_size 100G;

    # Root directory for the built Vue.js application
    root /usr/share/nginx/html;
    index index.html;

    # =================================================================
    # API PROXY RULES
    #
    # These specific locations are evaluated BEFORE the general SPA rule.
    # The order of these proxy rules matters.
    # =================================================================

    # 1. Standard API prefixes (highest priority for matching)
    location /api/ {
        proxy_pass http://hub-api:48888;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /org/ {
        proxy_pass http://hub-api:48888;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    # 2. Git LFS routes (critical for large file uploads/downloads)
    # Matches URLs like /kohaku/test-2.git/info/lfs/objects/batch
    location ~ \.git/info/lfs/ {
        proxy_pass http://hub-api:48888;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    # 3. File resolution routes (for downloads)
    # This is the most specific pattern and should be checked first.
    # Matches /models/user/repo/resolve/...
    location ~ ^/(models|datasets|spaces)/[^/]+/[^/]+/resolve/ {
        proxy_pass http://hub-api:48888;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    # This is the legacy pattern.
    # Matches /user/repo/resolve/...
    # By placing it after the more specific rule above, we avoid conflicts.
    location ~ ^/[^/]+/[^/]+/resolve/ {
        proxy_pass http://hub-api:48888;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }


    # =================================================================
    # FRONTEND SINGLE PAGE APP (SPA)
    #
    # This is the final fallback. If no API rule above matched,
    # Nginx assumes it's a frontend route and serves the SPA.
    # =================================================================
    location / {
        try_files $uri $uri/ /index.html;
    }
}