import secrets
from datetime import datetime, timedelta, timezone

import jwt
from passlib.context import CryptContext

from src.core.settings import settings


class AuthManager:
    pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

    @classmethod
    def verify_password(cls, plain_password, hashed_password):
        return cls.pwd_context.verify(plain_password, hashed_password)

    @classmethod
    def get_password_hash(cls, password):
        return cls.pwd_context.hash(password)

    @classmethod
    def create_access_token(cls, data: dict, expires_delta: timedelta | None = None):
        to_encode = data.copy()
        if expires_delta:
            expire = datetime.now(timezone.utc) + expires_delta
        else:
            expire = datetime.now(timezone.utc) + timedelta(
                minutes=settings.access_token.expire_minutes
            )
        to_encode.update({"exp": expire})
        encoded_jwt = jwt.encode(
            to_encode,
            settings.access_token.secret_key,
            algorithm=settings.access_token.algorithm,
        )
        return encoded_jwt

    @classmethod
    def create_refresh_token(cls) -> str:
        token_hash = secrets.token_urlsafe(32)
        return token_hash

    @classmethod
    def decode_access_token(cls, token: str, verify_exp: bool = True) -> dict:
        return jwt.decode(
            token,
            settings.access_token.secret_key,
            algorithms=[settings.access_token.algorithm],
            options={"verify_exp": verify_exp},
        )
