import os
from typing import Any, Mapping
from passlib.context import CryptContext
from datetime import UTC, datetime, timedelta
from jose import JWTError, jwt
from app.logger_config import Logger

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
_logger = Logger().logger


def hash_password(password: str) -> str:
    return pwd_context.hash(password)


def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)


# FIXME: Remove hard coded vars
SECRET_KEY = os.getenv("JWT_SECRET_KEY", "")
ALGORITHM = os.getenv("JWT_ALGORITHM", "HS256")
EXPIRATION_MINS = os.getenv("JWT_EXPIRATION_MINS", "10")


def create_access_token(
    data: dict, expires_delta: timedelta = timedelta(minutes=int(EXPIRATION_MINS))
):
    to_encode = data.copy()
    expire = datetime.now(UTC) + expires_delta
    to_encode.update({"exp": expire})

    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)


def decode_access_token(token: str) -> Mapping[Any, Any] | None:
    try:
        return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    except JWTError:
        _logger.exception(msg="Failed to Decode JWT", extra={"TOKEN": token})
        return None
