from fastapi import HTTPException, status
from jose import jwt, JWTError
from passlib.context import CryptContext
from app.core.config import get_settings
from app.core.constants import (
    ERR_NOT_VALID_CRED,
    ERR_INVALID_TOKEN
)

settings = get_settings()
pwd_context = CryptContext(schemes=["argon2"], deprecated="auto")

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)

# import bcrypt
# def hash_password(password: str) -> str:
#     return bcrypt.hashpw(
#         bytes(password, encoding="utf-8"),
#         bcrypt.gensalt(),
#     )
# def verify_password(plain_password: str, hashed_password: bytes) -> bool:
#     # Convert the plain_password to bytes if it's a string
#     plain_password_bytes = plain_password.encode('utf-8')
#     # Check if hashed_password is in the correct type (bytes)
#     if not isinstance(hashed_password, bytes):
#         raise TypeError("hashed_password should be of type 'bytes'")
#     # Perform bcrypt password comparison
#     return bcrypt.checkpw(plain_password_bytes, hashed_password)

def verify_token(token: str, token_type: str = "access"):
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        if payload.get("type") != token_type:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail=ERR_INVALID_TOKEN,
            )
        return payload
    except JWTError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=ERR_NOT_VALID_CRED,
        )
