# Paperless NGX session isolation configuration
# This file overrides default session settings to prevent conflicts with other Django apps

import os
from paperless.settings import *

# Override session cookie name to prevent conflicts with main Django app
SESSION_COOKIE_NAME = 'paperless_sessionid'

# Also change CSRF cookie name for good measure
CSRF_COOKIE_NAME = 'paperless_csrftoken'

# Scope cookies to Paperless path to avoid conflicts
SESSION_COOKIE_PATH = '/paperless/'
CSRF_COOKIE_PATH = '/paperless/'

# Different secret key salt to ensure session isolation
SESSION_COOKIE_SALT = 'paperless.sessions'

# Fix login redirect to stay within Paperless scope  
# Use environment variable if set, otherwise default to /paperless/
LOGIN_REDIRECT_URL = os.getenv('PAPERLESS_LOGIN_REDIRECT_URL', '/paperless/')
LOGOUT_REDIRECT_URL = os.getenv('PAPERLESS_LOGOUT_REDIRECT_URL', '/paperless/')
LOGIN_URL = '/paperless/accounts/login/'

# Ensure Force Script Name for proper URL handling behind proxy
FORCE_SCRIPT_NAME = os.getenv('PAPERLESS_FORCE_SCRIPT_NAME', '/paperless')

# Additional URL configuration for proper reverse proxy support
USE_X_FORWARDED_HOST = True
USE_X_FORWARDED_PORT = True

# Static and media URL configuration for subpath
STATIC_URL = '/paperless/static/'
MEDIA_URL = '/paperless/media/'

# Fix any hardcoded redirects in Paperless
ACCOUNT_LOGOUT_REDIRECT_URL = '/paperless/'

# Force Django to always use the paperless prefix for authentication URLs
LOGIN_URL = '/paperless/accounts/login/'

# Override Django's redirect behavior for authentication  
# This ensures that after login, if no next parameter is provided or if next='/', 
# it redirects to /paperless/ instead
def fix_login_redirect(original_redirect_url):
    """Custom redirect logic to keep users within Paperless scope"""
    if not original_redirect_url or original_redirect_url == '/':
        return '/paperless/'
    elif original_redirect_url.startswith('/') and not original_redirect_url.startswith('/paperless/'):
        return '/paperless/'
    return original_redirect_url

# Monkey patch Django's login view to fix redirect behavior
import django.contrib.auth.views
original_get_success_url = django.contrib.auth.views.LoginView.get_success_url

def patched_get_success_url(self):
    url = original_get_success_url(self)
    return fix_login_redirect(url)

django.contrib.auth.views.LoginView.get_success_url = patched_get_success_url