# settings.py
import os
from pathlib import Path
from decouple import config, Csv

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

# ── Core ───────────────────────────────────────────────────────────────────────
SECRET_KEY = config('SECRET_KEY')  # Fail hard if not set in .env
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='localhost,127.0.0.1', cast=Csv())

# ── Django Admin URL ───────────────────────────────────────────────────────────
# Keep this secret in .env — never use the default '/admin/' in production.
# Example .env entry:  DJANGO_ADMIN_URL=myadmin-secret-path
DJANGO_ADMIN_URL = config('DJANGO_ADMIN_URL', default='admin')

# ── CSRF ───────────────────────────────────────────────────────────────────────
# Trusted origins for CSRF — required in production (and avoids CSRF errors)
CSRF_TRUSTED_ORIGINS = config(
    'CSRF_TRUSTED_ORIGINS',
    default='https://app.swiftpos.ng',
    cast=Csv()
)

# ── Security & HTTPS (Proxy, SSL, Cookies) ───────────────────────────────────
# Required for Django to know it's behind an HTTPS proxy (e.g., cPanel/Nginx)
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Force redirect HTTP -> HTTPS (Defaults to True in production where DEBUG=False)
SECURE_SSL_REDIRECT = config('SECURE_SSL_REDIRECT', default=not DEBUG, cast=bool)

# Cookie settings — secure in production, relaxed locally
CSRF_COOKIE_SECURE = config('CSRF_COOKIE_SECURE', default=not DEBUG, cast=bool)
SESSION_COOKIE_SECURE = config('SESSION_COOKIE_SECURE', default=not DEBUG, cast=bool)
CSRF_COOKIE_SAMESITE = 'Lax'
SESSION_COOKIE_SAMESITE = 'Lax'

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'rest_framework',
    'rest_framework.authtoken',
    'companies',       # ← Multi-tenant company layer
    'core',
    'inventory',
    'sales',
    'accounts',
    'subscriptions',   # ← SaaS billing layer
    'analytics',       # ← Business Intelligence & Insights
    'corsheaders',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    # ✅ WhiteNoise serves static files in production (no collectstatic issues)
    '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',
    'companies.middleware.CompanyMiddleware',   # Phase 4: resolve request.company
    'core.middleware.ActivationMiddleware',     # kept as no-op stub
    'core.middleware.LoginRateLimitMiddleware', # 🛡️ IP-based login brute-force protection
]

ROOT_URLCONF = 'pos_system.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'core.context_processors.swiftpos_settings',
            ],
        },
    },
]

WSGI_APPLICATION = 'pos_system.wsgi.application'


# # ── Database ───────────────────────────────────────────────────────────────────
DATABASES = {
    'default': {
        'ENGINE': config('DB_ENGINE', default='django.db.backends.postgresql'),
        'NAME': config('DB_NAME', default='sw_db'),
        'USER': config('DB_USER', default='postgres'),
        'PASSWORD': config('DB_PASSWORD', default=''),
        'HOST': config('DB_HOST', default='localhost'),
        'PORT': config('DB_PORT', default='5432'),
    }
}

# ── Auth ───────────────────────────────────────────────────────────────────────
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'},
]
AUTH_USER_MODEL = 'accounts.CustomUser'

# ── Internationalisation ───────────────────────────────────────────────────────
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Africa/Lagos'
USE_I18N = True
USE_TZ = False

# ── Static & Media ─────────────────────────────────────────────────────────────
STATIC_URL = config('STATIC_URL', default='/static/')
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'staticfiles'

# ✅ WhiteNoise: serve compressed static files even with DEBUG=False (admin styles included)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

MEDIA_URL = config('MEDIA_URL', default='/media/')
MEDIA_ROOT = BASE_DIR / 'media'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# ── Email (SSL SMTP) ───────────────────────────────────────────────────────────
EMAIL_HOST = config('EMAIL_HOST', default='mail.swiftpos.ng')
EMAIL_PORT = config('EMAIL_PORT', default=465, cast=int)
EMAIL_USE_SSL = config('EMAIL_USE_SSL', default=True, cast=bool)
EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=False, cast=bool)
EMAIL_HOST_USER = config('EMAIL_HOST_USER', default='')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default='')
DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL', default='SwiftPOS <contact@swiftpos.ng>')

if DEBUG and not EMAIL_HOST_USER:
    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
else:
    EMAIL_BACKEND = config('EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend')

# Admin emails for alerts
ADMIN_EMAIL = config('ADMIN_EMAIL', default='')

# ── Site URL (used for absolute links in emails) ───────────────────────────────
# Required in .env:  SITE_URL=https://app.swiftpos.ng
SITE_URL = config('SITE_URL')

# ── App-specific settings ──────────────────────────────────────────────────────
WHATSAPP_NUMBER = config('WHATSAPP_NUMBER', default='')
LOW_STOCK_THRESHOLD = config('LOW_STOCK_THRESHOLD', default=10, cast=int)


# ── Monnify Payment Gateway ─────────────────────────────────────────────────────
MONNIFY_API_KEY       = config('MONNIFY_API_KEY', default='')
MONNIFY_SECRET_KEY    = config('MONNIFY_SECRET_KEY', default='')
MONNIFY_CONTRACT_CODE = config('MONNIFY_CONTRACT_CODE', default='')
MONNIFY_BASE_URL      = config('MONNIFY_BASE_URL', default='https://api.monnify.com')
TRIAL_DURATION_DAYS   = config('TRIAL_DURATION_DAYS', default=3, cast=int)

# ── Web AI Integration ────────────────────────────────────────────────────────
AI_API_PROVIDER = config('AI_API_PROVIDER', default='openrouter')
AI_API_URL      = config('AI_API_URL', default='https://openrouter.ai/api/v1/chat/completions')
AI_API_KEY      = config('AI_API_KEY', default='')
AI_API_MODEL    = config('AI_API_MODEL', default='meta-llama/llama-3-8b-instruct')
AI_DAILY_LIMIT  = config('AI_DAILY_LIMIT', default=50, cast=int)

# ── Django REST Framework ──
# Allow all origins, or restrict to specific origins
# ⚠ IMPORTANT: Set CORS_ALLOW_ALL_ORIGINS=False in production .env
CORS_ALLOW_ALL_ORIGINS = config('CORS_ALLOW_ALL_ORIGINS', default=False, cast=bool)

# ── Password Reset Settings ───────────────────────────────────────────────────
# Token validity duration: 30 minutes (1800 seconds)
PASSWORD_RESET_TIMEOUT = 1800
CORS_ALLOWED_ORIGINS = config('CORS_ALLOWED_ORIGINS', default='http://localhost:8000,http://127.0.0.1:8000', cast=Csv())
CORS_ALLOWED_ORIGIN_REGEXES = [
    r"^http://localhost:\d+$",
    r"^http://127\.0\.0\.1:\d+$",
]
CORS_ALLOW_CREDENTIALS = True

# ── Django REST Framework ──────────────────────────────────────────────────────
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_RENDERER_CLASSES': (
        [
            'rest_framework.renderers.JSONRenderer',
            'rest_framework.renderers.BrowsableAPIRenderer',
        ] if DEBUG else [
            'rest_framework.renderers.JSONRenderer',
        ]
    ),
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/hour',
        'user': '2000/hour',
    },
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 50,
}
LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/'

# ── Security Headers ──────────────────────────────────────────────────────────
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True      # Legacy header; harmless for older browsers
X_FRAME_OPTIONS = 'DENY'

# ── Session Security ──────────────────────────────────────────────────────────
SESSION_COOKIE_HTTPONLY = True         # Prevent JS from reading the session cookie
SESSION_COOKIE_AGE = config('SESSION_COOKIE_AGE', default=86400, cast=int)  # 24 hours (fallback/maximum for non-remember-me)
SESSION_EXPIRE_AT_BROWSER_CLOSE = config('SESSION_EXPIRE_AT_BROWSER_CLOSE', default=False, cast=bool)
SESSION_SAVE_EVERY_REQUEST = True      # Reset the session timer on every page visit (keeps active users logged in)


# -- Paystack Payment Gateway ------------------------------------------
PAYSTACK_PUBLIC_KEY  = config('PAYSTACK_PUBLIC_KEY', default='')
PAYSTACK_SECRET_KEY  = config('PAYSTACK_SECRET_KEY', default='')

# -- WhatsApp / SMS (Termii or compatible provider) -------------------
WHATSAPP_API_URL      = config('WHATSAPP_API_URL', default='')
WHATSAPP_API_KEY      = config('WHATSAPP_API_KEY', default='')
SMS_API_KEY           = config('SMS_API_KEY', default='')
SMS_SENDER_ID         = config('SMS_SENDER_ID', default='SwiftPOS')
ADMIN_WHATSAPP_NUMBER = config('ADMIN_WHATSAPP_NUMBER', default='')
