# Enable RewriteEngine
RewriteEngine On

# Handle API routes - always redirect to PHP backend, even if a static file exists
RewriteRule ^api/(.*)$ backend/public/index.php [QSA,L]

# Handle Next.js static files
RewriteCond %{REQUEST_URI} ^/_next/(.*)$
RewriteRule ^_next/(.*)$ _next/$1 [L]

# Handle static files in the public directory
RewriteCond %{REQUEST_URI} ^/public/(.*)$
RewriteRule ^public/(.*)$ public/$1 [L]

# If requested resource exists as a file or directory, serve it directly (except /api/*)
RewriteCond %{REQUEST_URI} !^/api/
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# If the requested resource doesn't exist, serve index.html
RewriteRule ^ index.html [L]

# Prevent .txt files from being fetched as RSC payloads (except robots.txt)
<FilesMatch "\.txt$">
  <IfModule mod_headers.c>
    # Skip robots.txt
    SetEnvIf Request_URI "^/robots\.txt$" skip_headers=1
    Header set Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate" env=!skip_headers
    Header set Content-Type "text/plain; charset=utf-8" env=!skip_headers
  </IfModule>
</FilesMatch>
