from datetime import UTC, datetime, timedelta

from fastapi import HTTPException, status
from jose import JWTError, jwt
from pwdlib import PasswordHash

from app.core.config import settings

password_hash = PasswordHash.recommended()

ALGORITHM = "HS256"
ACCESS_TOKEN_TYPE = "access"


def get_access_token_expire_seconds() -> int:
    return settings.access_token_expire_minutes * 60


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


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


def create_access_token(subject: str) -> str:
    issued_at = datetime.now(UTC)
    expire = issued_at + timedelta(minutes=settings.access_token_expire_minutes)

    payload = {
        "sub": subject,
        "iat": issued_at,
        "exp": expire,
        "iss": settings.jwt_issuer,
        "type": ACCESS_TOKEN_TYPE,
    }

    return jwt.encode(
        payload,
        settings.secret_key,
        algorithm=ALGORITHM,
    )


def verify_access_token(token: str) -> str:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Nicht authentifiziert",
        headers={"WWW-Authenticate": "Bearer"},
    )

    try:
        payload = jwt.decode(
            token,
            settings.secret_key,
            algorithms=[ALGORITHM],
            issuer=settings.jwt_issuer,
        )
        subject = payload.get("sub")
        token_type = payload.get("type")
    except JWTError as exc:
        raise credentials_exception from exc

    if not isinstance(subject, str) or not subject:
        raise credentials_exception

    if token_type != ACCESS_TOKEN_TYPE:
        raise credentials_exception

    return subject
