from pathlib import Path
from corsheaders.defaults import default_headers

# settings.py
from datetime import timedelta
import pytz
from cryptography.hazmat.primitives import hashes

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-6trd#b(xs^iyz^lvqbrk+!gf_2&1-o+$$0v$838n_y^&zyg0*6"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["mis.api.zhwak.com"]


AUTH_USER_MODEL = "account.User"

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "account",
    "shop_management",
    "rest_framework",
    "rest_framework.authtoken",
    "knox",
    "corsheaders",
    "django_filters",
    "rest_framework_simplejwt",
]

MIDDLEWARE = [
    # Highest possible so preflight/error responses still get CORS headers.
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "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",
    "account.middleware.TemporaryVerificationMiddleware",
    "account.middleware.CurrentUserMiddleware",
]

ROOT_URLCONF = "backend.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "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 = "backend.wsgi.application"


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'zhwaongl_mis_db',
        'USER': 'zhwaongl_mis_user',
        'PASSWORD': 'ssWTJAlGn=!Zn[0C',
        'HOST': 'localhost',   # or your DB host (e.g. 127.0.0.1 or remote IP)
        'PORT': '3306',
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        },
    }
}


# 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"

# Other settings...

# Set the time zone to Kabul
TIME_ZONE = "Asia/Kabul"

# Ensure that Django uses timezone-aware datetimes
USE_TZ = True

# Optional: Set the default timezone for the application
pytz.timezone(TIME_ZONE)  # This is just to verify the timezone is set correctly


USE_I18N = True


AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
]


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "static"

MEDIA_URL = "media/"
MEDIA_ROOT = BASE_DIR / "media"

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = False

CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:3000",
    "https://mis.zhwak.com",
    "http://mis.zhwak.com",
    "https://api.zhwak.com",
]

CSRF_TRUSTED_ORIGINS = [
    "https://mis.zhwak.com",
    "http://mis.zhwak.com",
    "https://api.zhwak.com",
    "http://localhost:3000",
    "http://127.0.0.1:3000",
]

CORS_ALLOW_METHODS = [
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
]

# Allow custom tenant header used for branch-scoped auth
CORS_ALLOW_HEADERS = list(default_headers) + [
    "x-selected-shop",
    "x-admin-branch-context",
]

CORS_PREFLIGHT_MAX_AGE = 86400

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication",
        "knox.auth.TokenAuthentication",
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ],
    "DEFAULT_PARSER_CLASSES": [
        "rest_framework.parsers.JSONParser",
        "rest_framework.parsers.MultiPartParser",
        "rest_framework.parsers.FormParser",
    ],
}


# In settings.py or wherever file validations are set up
ALLOWED_IMAGE_EXTENSIONS = [
    "bmp",
    "dib",
    "gif",
    "jfif",
    "jpg",
    "jpeg",
    "png",
    "webp",
    ...,
]


TWILIO_ACCOUNT_SID = "AC05772a8f7589a923a55c2d2be35a0975"
TWILIO_AUTH_TOKEN = "3c1d3fb74919d726e98301d807613e30"  # replace this with the correct value from Twilio
TWILIO_FROM_NUMBER = "+15005550006"


EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 465  # For SSL
EMAIL_USE_SSL = True
EMAIL_USE_TLS = False  # Set to False because we're using SSL
EMAIL_HOST_USER = "asanbawar100@gmail.com"  # Replace with your Gmail address
EMAIL_HOST_PASSWORD = "phbz oywa jfla mvrz"  # Replace with your Gmail app password (not your regular password)
DEFAULT_FROM_EMAIL = "sender name asanbawar100@gmail.com"


REST_KNOX = {
    "AUTH_TOKEN_CHARACTER_LENGTH": 64,
    "TOKEN_TTL": timedelta(days=365),
    "USER_SERIALIZER": "account.serializer.UserSerializer",
    "TOKEN_LIMIT_PER_USER": None,
    "AUTO_REFRESH": False,
}


EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "asanbawar.com"
EMAIL_USE_SSL = True
EMAIL_PORT = 465
EMAIL_HOST_USER = "otp@asanbawar.com"
EMAIL_HOST_PASSWORD = "$%=mC2DV(t]B"
