from decouple import config

from .base import *  # noqa: F401,F403

DEBUG = False

# Railway assigns a public domain automatically and exposes it via this env
# var; trust it without requiring it to be duplicated into ALLOWED_HOSTS.
_railway_domain = config('RAILWAY_PUBLIC_DOMAIN', default='')
if _railway_domain:
    ALLOWED_HOSTS = [*ALLOWED_HOSTS, _railway_domain]  # noqa: F405

# Railway (like Heroku/Render/Fly) terminates TLS at its edge proxy and
# forwards plain HTTP to the app, setting X-Forwarded-Proto to say so. Without
# this, SECURE_SSL_REDIRECT sees every request as HTTP and redirects it —
# including CORS preflight OPTIONS requests, which browsers refuse to follow,
# breaking every cross-origin request from the Vercel frontend.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

SECURE_SSL_REDIRECT = config('SECURE_SSL_REDIRECT', default=True, cast=bool)
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True

AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME', default='')
AWS_S3_REGION_NAME = config('AWS_S3_REGION_NAME', default='')

STORAGES = {
    # Falls back to local disk storage until an S3 bucket is configured, so
    # deploys don't crash on first file upload for lack of AWS credentials.
    # Note: Railway's filesystem is ephemeral, so uploads (logos, stamps,
    # signatures) won't survive a redeploy until an S3 bucket is set.
    'default': (
        {'BACKEND': 'storages.backends.s3.S3Storage'}
        if AWS_STORAGE_BUCKET_NAME
        else {'BACKEND': 'django.core.files.storage.FileSystemStorage'}
    ),
    'staticfiles': {
        'BACKEND': 'whitenoise.storage.CompressedManifestStaticFilesStorage',
    },
}

# Requires EMAIL_HOST / EMAIL_HOST_USER / EMAIL_HOST_PASSWORD set in the environment.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
