"""
JWT tokens — the Django adapter over the shared core (`mizan_core.auth.jwt`).

The token logic (mint/decode/refresh, `JWTUser`, `TokenPair`, `TokenPayload`)
lives in the core; this module binds it to Django settings and keeps the
session-revocation check (`validate_session`), which is Django-session-specific.
"""

from __future__ import annotations

from mizan_core.auth import jwt as _core_jwt
from mizan_core.auth.jwt import JWTConfig, JWTUser, TokenPair, TokenPayload

from .settings import get_settings

__all__ = [
    "TokenPair",
    "TokenPayload",
    "JWTUser",
    "create_access_token",
    "create_refresh_token",
    "create_token_pair",
    "decode_token",
    "validate_session",
    "refresh_tokens",
]


def _config() -> JWTConfig:
    s = get_settings()
    return JWTConfig(
        private_key=s.private_key,
        public_key=s.public_key,
        algorithm=s.algorithm,
        access_token_expires_in=s.access_token_expires_in,
        refresh_token_expires_in=s.refresh_token_expires_in,
    )


def create_access_token(user_id, session_key, *, is_staff=False, is_superuser=False) -> str:
    return _core_jwt.create_access_token(user_id, session_key, _config(),
                                         is_staff=is_staff, is_superuser=is_superuser)


def create_refresh_token(user_id, session_key, *, is_staff=False, is_superuser=False) -> str:
    return _core_jwt.create_refresh_token(user_id, session_key, _config(),
                                          is_staff=is_staff, is_superuser=is_superuser)


def create_token_pair(user_id, session_key, *, is_staff=False, is_superuser=False) -> TokenPair:
    return _core_jwt.create_token_pair(user_id, session_key, _config(),
                                       is_staff=is_staff, is_superuser=is_superuser)


def decode_token(token: str, expected_type: str | None = None) -> TokenPayload | None:
    return _core_jwt.decode_token(token, _config(), expected_type=expected_type)


def validate_session(session_key: str) -> bool:
    """Immediate-logout revocation: is this Django session still alive?

    Honors `JWT_VALIDATE_SESSION` — when disabled, always True. This is the one
    Django-session-bound piece; the core's `refresh_tokens` takes it as an
    injected `session_validator`.
    """
    from importlib import import_module

    from django.conf import settings as django_settings

    if not get_settings().validate_session:
        return True

    engine = import_module(django_settings.SESSION_ENGINE)
    session = engine.SessionStore(session_key=session_key)
    return session.exists(session_key)


def refresh_tokens(refresh_token: str) -> TokenPair | None:
    return _core_jwt.refresh_tokens(refresh_token, _config(), session_validator=validate_session)
