# Habilitar mod_rewrite
RewriteEngine On

# Forzar HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# ---------- REGLAS ESPECÍFICAS PARA BACKEND ----------
# Si la URL comienza con /backend/, déjala pasar sin redirección
RewriteCond %{REQUEST_URI} ^/backend/ [NC]
RewriteRule ^ - [L]

# ---------- REGLAS PARA FRONTEND ----------
# Si NO es un archivo existente
RewriteCond %{REQUEST_FILENAME} !-f
# Si NO es un directorio existente
RewriteCond %{REQUEST_FILENAME} !-d
# Redirige todo lo demás al index.html principal
RewriteRule ^(.*)$ /index.html [L]

# ---------- CONFIGURACIÓN GENERAL ----------
# Deshabilitar listado de directorios
Options -Indexes

# Configurar CORS para API
<IfModule mod_headers.c>
    # Para todas las respuestas
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"
    
    # Para respuestas OPTIONS (preflight)
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>

# Manejo de errores
ErrorDocument 404 /frontend/404.html
ErrorDocument 500 /frontend/500.html

# Seguridad - bloquear archivos sensibles
<FilesMatch "\.(env|config|log|sql|ini|htaccess|htpasswd)$">
    Order allow,deny
    Deny from all
</FilesMatch>