"""
Django settings for ThikaConnect
"""

from pathlib import Path
from datetime import timedelta

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = "django-insecure-hc-#_fhn@81)ag4hu+y%@l9*4h@st6ellaw%6rjlh*qtmm1dt)"
DEBUG = False
ALLOWED_HOSTS = ["api.scopesafaris.com", "127.0.0.1", "localhost"]

INSTALLED_APPS = [
    "daphne",

    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    "rest_framework",
    "rest_framework_simplejwt",
    "corsheaders",
    "channels",

    "account",
    "followers",
    "posts",
    "status",
    "chat",
    "community",
    "friends",
    "inbox",
    "announcements",
    "notifications",
    "wallet",
]

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",        # ← MUST be absolutely first
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

# ── CORS — allow everything in development ──
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOW_CREDENTIALS      = True
CORS_ORIGIN_ALLOW_ALL = False   # legacy alias — belt and suspenders
CORS_ALLOW_PRIVATE_NETWORK  = True

CORS_ALLOWED_ORIGINS = [
    "http://localhost:5173",
    "http://localhost:5174",
    "http://localhost:5175",
    "http://127.0.0.1:5173",
    "http://127.0.0.1:5174",
    "http://127.0.0.1:5175",
]

CORS_ALLOWED_ORIGIN_REGEXES = [
    r"^http://localhost:\d+$",
    r"^http://127\.0\.0\.1:\d+$",
]

CORS_ALLOW_HEADERS = list([
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
])

CORS_ALLOW_METHODS = list([
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
])

CORS_PREFLIGHT_MAX_AGE = 86400
CORS_URLS_REGEX        = r"^.*$"   # apply CORS to ALL routes

ROOT_URLCONF = "config.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "config.wsgi.application"
ASGI_APPLICATION  = "config.asgi.application"

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]

LANGUAGE_CODE = "en-us"
TIME_ZONE     = "Africa/Nairobi"
USE_I18N      = True
USE_TZ        = True

STATIC_URL  = "/static/"
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
STATIC_ROOT = BASE_DIR / "staticfiles"

MEDIA_URL  = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

AUTH_USER_MODEL = "account.User"

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ),
    "DEFAULT_PERMISSION_CLASSES": (
        "rest_framework.permissions.IsAuthenticated",
    ),
}

SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME":  timedelta(days=3),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=30),
    "AUTH_HEADER_TYPES":      ("Bearer",),
}

STATUS_EXPIRY_SECONDS = 86400
STATUS_MAX_SIZE       = 10 * 1024 * 1024

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# ── EMAIL (Gmail SMTP) ──
EMAIL_BACKEND       = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "localhost"
EMAIL_PORT = 25
EMAIL_USE_TLS = False
EMAIL_HOST_USER = "noreply@scopesafaris.com"
EMAIL_HOST_PASSWORD = "ThikaConnect@2026"
DEFAULT_FROM_EMAIL = "ThikaConnect <noreply@scopesafaris.com>"

PASSWORD_RESET_TIMEOUT = 3600
# Production CORS configuration
CORS_ALLOWED_ORIGINS = [
    "https://mku-connect-lilac.vercel.app",
    "https://scopesafaris.com",
    "https://www.scopesafaris.com",
]

CSRF_TRUSTED_ORIGINS = [
    "https://mku-connect-lilac.vercel.app",
    "https://scopesafaris.com",
    "https://www.scopesafaris.com",
]
