"""
Django settings for kwara_api_django project.

Generated by 'django-admin startproject' using Django 5.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-y%%)=e_x*4o=q!22c6&9t5t#leml16dj0rv7)y#uz2vajzt7_('

from datetime import timedelta
from corsheaders.defaults import default_headers

# from django.conf import settings
# from rest_framework_simplejwt.authentication import JWTAuthentication

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# ALLOWED_HOSTS = ["127.0.0.1", "localhost", "kbs-internet-banking.net"]
# ALLOWED_HOSTS = ["*"]
ALLOWED_HOSTS = [
    "kbs-internet-banking.net",
    "backend.kbs-internet-banking.net",
]


CORS_ALLOWED_ORIGINS = [
    'http://localhost:3000',  # React app origin
    'http://localhost:8000',  # React app origin
    'http://localhost:5173',  # Vite app origin
    'https://kbs-internet-banking.net',
    'https://backend.kbs-internet-banking.net',
    'https://test.kbs-internet-banking.net',
]

CORS_ORIGIN_WHITELIST = [
    'http://localhost:3000',
    'http://localhost:8000',
    'http://localhost:5173',
    'https://kbs-internet-banking.net',
    'https://backend.kbs-internet-banking.net',
    'https://test.kbs-internet-banking.net',
]


CORS_ALLOW_HEADERS = list(default_headers) + [
    "Authorization",
    "Member-ID",  # Add your custom header here
]

CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_HTTPONLY = True
CSRF_TRUSTED_ORIGINS = [
    'http://localhost:3000',
    'http://localhost:8000',
    'https://kbs-internet-banking.net',
    'https://backend.kbs-internet-banking.net',
]


SESSION_ENGINE = 'django.contrib.sessions.backends.db'  # Default, stores sessions in the database
SESSION_COOKIE_AGE = 3600  # 20 minutes
SESSION_SAVE_EVERY_REQUEST = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True  # Expire session on browser close
# SESSION_COOKIE_SECURE = False  # Set to True if using HTTPS
# SESSION_EXPIRE_AT_BROWSER_CLOSE = True
# CSRF_COOKIE_SECURE = False # Set to True if using HTTPS
SECURE_HSTS_SECONDS = 31536000  # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
# USE_X_FORWARDED_HOST = True
# SECURE_PROXY_SSL_HEADER = None
# SECURE_SSL_REDIRECT = False

# For live
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
# SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')



SIMPLE_JWT = {
    'USER_ID_FIELD': 'sacco_user_id',
    'USER_ID_CLAIM': 'user_id',
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,
    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,
    'AUTH_HEADER_TYPES': ('Bearer',),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
    'AUTH_HEADER_PREFIX': 'Bearer',
    'AUTH_COOKIE': None,
    'AUTH_COOKIE_PATH': '/',
    'AUTH_COOKIE_DOMAIN': None,
    'AUTH_COOKIE_SECURE': False,
    'AUTH_COOKIE_HTTPONLY': True,
    'AUTH_COOKIE_SAMESITE': None,
    'AUTH_COOKIE_NAME': 'access_token',
}

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
}

INTERNAL_IPS = [
    # ...
    "127.0.0.1",
    # ...
]


# Application definition

INSTALLED_APPS = [
    'jet',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "api",
    'corsheaders',
    'rest_framework',
    'rest_framework_simplejwt',
    'paypal.standard.ipn',
    # "debug_toolbar",
    'django_daraja',
    'django_extensions',
    # 'silk',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # 'silk.middleware.SilkyMiddleware'
]
    # "debug_toolbar.middleware.DebugToolbarMiddleware",
    # 'rest_framework_simplejwt.middleware.JWTAuthenticationMiddleware',

ROOT_URLCONF = 'kwara_api_django.urls'
import os

# DJANGO_ENV = os.getenv('DJANGO_ENV', 'development')

# if DJANGO_ENV == 'development':
#     DEBUG = True
#     KWARA_CLIENT_ID = '378691dd4e1d586aa48e5d34569e21f899052b7808c18029415fbd4f0fa225d0'
#     KWARA_CLIENT_SECRET = "3dc8c392a02d183716f4d3adc211e09cb3033bc96560879505a49f55e7dc6d70"
# else:
#     DEBUG = False
#     KWARA_CLIENT_ID = 'hW5DhVcUHSb06W45ERIqdXX6D6C9CElC1KXbgkDWomQ'
#     KWARA_CLIENT_SECRET = "3tEroB79viucZc5sg6Fjqf6TpOevyXY_BQg-IaYxxpE"

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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',
            ],
        },
    },
]

WSGI_APPLICATION = 'kwara_api_django.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

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


# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

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',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

BASE_MEDIA = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATIC_URL = 'static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# MEDIA_ROOT = BASE_DIR / 'media'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')  # Adjust BASE_DIR as necessary


# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

AUTH_USER_MODEL = 'api.CustomUser'
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'kbs-internet-banking.net'  # Microsoft 365 SMTP server
EMAIL_PORT = 465  # Use 587 for TLS && 465 for SSL
EMAIL_USE_TLS = False  # Microsoft 365 requires TLS && False for SSL
EMAIL_USE_SSL = True  # Must be False for TLS && True for SSL
EMAIL_HOST_USER = 'info@kbs-internet-banking.net'  # Your Microsoft 365 email
EMAIL_HOST_PASSWORD = 'Justice@123#'  # Use an App Password if MFA is enabled
DEFAULT_FROM_EMAIL = 'info@kbs-internet-banking.net'

# STANBIC CREDENTIALS
STANBIC_CLIENT_ID = "bde1801356912a01adc1e2b50fc4879c"
STANBIC_CLIENT_SECRET = "42a920ac85b542486ca5ca6ebbe57a60"
STANBIC_TOKEN_URL = "https://api.connect.stanbicbank.co.ke/api/sandbox/auth/oauth2/token"
STANBIC_SCOPE = "payments"
KBS_FROM_ACCOUNT = "0100013868365"
KBS_FROM_PHONE="254792009556"

# PAYPAL
PAYPAL_CLIENT_ID = 'AWSJ-1T2RTcjFqu6aVWuxF4BaMUcq1IozYGsl_bldQC0VCHgh4f4MlCLT4ndZfmo9x6mlLNG7mzDq6YH'
PAYPAL_SECRET = 'EFo4D1rFAKDrzkOEGhqfpxv81YEJ-ikxhV-ZUsffnmijZQZ2o_X1fSzFSPqLArpGOsNDq5HMImSVGKND'
PAYPAL_RECEIVER_EMAIL = "sb-vzd5k29858989@business.example.com"
PAYPAL_TEST = True
PAYPAL_MODE = 'sandbox'  # or 'live' for production

# MPESA
# The Mpesa environment to use
# Possible values: sandbox, production

MPESA_ENVIRONMENT = 'production'

# Credentials for the daraja app

MPESA_CONSUMER_KEY = 'meGyZMIe69vAC2a033yZuSKNV3vXPkFu'
MPESA_CONSUMER_SECRET = 'IuNUxkjyGquGaclu'

#Shortcode to use for transactions. For sandbox  use the Shortcode 1 provided on test credentials page

MPESA_SHORTCODE = '400444'

# Shortcode to use for Lipa na MPESA Online (MPESA Express) transactions
# This is only used on sandbox, do not set this variable in production
# For sandbox use the Lipa na MPESA Online Shorcode provided on test credentials page

MPESA_EXPRESS_SHORTCODE = '400444'

# Type of shortcode
# Possible values:
# - paybill (For Paybill)
# - till_number (For Buy Goods Till Number)

MPESA_SHORTCODE_TYPE = 'paybill'

# Lipa na MPESA Online passkey
# Sandbox passkey is available on test credentials page
# Production passkey is sent via email once you go live

MPESA_PASSKEY = '8b8cefc5ffee270b3831aeaf4378df5181f92c487149e5b2acd37b3ec1295a26'

# Username for initiator (to be used in B2C, B2B, AccountBalance and TransactionStatusQuery Transactions)

MPESA_INITIATOR_USERNAME = 'testapi'

# Plaintext password for initiator (to be used in B2C, B2B, AccountBalance and TransactionStatusQuery Transactions)

MPESA_INITIATOR_SECURITY_CREDENTIAL = 'apxQrkhc1k3UkJZKD/LOnHQfot1wX5ZZ+5H3FF/LSshc3IcPE/nbavH5O+/S90oJGL9Al7MzfeJsgDWcrTzNIe1WCaMz2V1bxf+QfDaRFTlPb+I2uVNY7bvQkkg3WT8dGi7AqBZ9s0A4PIuwBu2hitcjGEoZL597uE4RNW99ZyTYJQ9qylEFwCFzVvzm9nLT9W0D8cajlgfnYwFVn/t77aulUViMISdznUIY38NAMt0V+TUULkCJYrSPsORjtR/SllOQFjJWrEky/p+SQf6UhMZpCJ5X+zH5LlodXA3EUbbKYg4uARREeSBAUmIW08T/Ih1JePb+36l7QBpI0gT4bg=='
