import uuid

import jwt
import redis as redis_lib
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session

from app.core import security
from app.db.redis import get_redis
from app.db.session import get_db
from app.models.user import User, UserRole
from app.services import token_blacklist

bearer_scheme = HTTPBearer(auto_error=True)


def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
    db: Session = Depends(get_db),
    redis: redis_lib.Redis = Depends(get_redis),
) -> User:
    credentials_error = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials.",
        headers={"WWW-Authenticate": "Bearer"},
    )

    try:
        payload = security.decode_access_token(credentials.credentials)
        user_id = uuid.UUID(payload.get("sub"))
        issued_at = int(payload["iat"])
    except (jwt.PyJWTError, ValueError, TypeError, KeyError) as exc:
        raise credentials_error from exc

    # This specific token was blacklisted by /auth/logout, or every
    # token issued before some point was blacklisted in bulk by
    # app.services.tokens.rotate_refresh_token (reuse/theft detected)
    # — see app.services.token_blacklist for both.
    if token_blacklist.is_access_token_blacklisted(redis, credentials.credentials):
        raise credentials_error
    # <=, not <: JWT `exp`/`iat` only have second-granularity, so a
    # token issued in the same wall-clock second as the invalidation
    # event must still be treated as "before" it — the far more likely
    # case is that's the very token that got compromised, not a
    # brand-new legitimate one that happened to land in the same
    # second. Erring toward over-invalidation (an extra "log in again"
    # in that rare coincidence) is the safe direction here, not under-
    # invalidation (a compromised token surviving the mass revocation
    # that was specifically meant to kill it).
    invalidated_before = token_blacklist.get_user_invalidated_before(redis, user_id)
    if invalidated_before is not None and issued_at <= invalidated_before:
        raise credentials_error

    user = db.get(User, user_id)
    if user is None or not user.is_active:
        raise credentials_error
    return user


def require_role(*roles: UserRole):
    """Dependency factory: restrict an endpoint to specific roles.
    See app.api.v1.endpoints.admin for its first real use."""

    def dependency(current_user: User = Depends(get_current_user)) -> User:
        if current_user.role not in {role.value for role in roles}:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="You don't have permission to do this.",
            )
        return current_user

    return dependency
