"""FastAPI dependencies for authentication."""

from __future__ import annotations

from typing import Any

from fastapi import Depends, HTTPException, Request, status

from aura_auth._core.protocols import UserProtocol


def get_aura_auth(request: Request) -> Any:
    """Return the ``AuraAuth`` instance attached to ``app.state``."""
    return request.app.state.aura_auth


async def current_user(request: Request) -> UserProtocol[Any]:
    """Return the authenticated user or raise 401."""
    aura = get_aura_auth(request)
    token = await aura.transport.get_token(request)
    if token is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
    user = await aura.manager.verify_token(token)
    if user is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
    return user


async def current_active_user(user: UserProtocol[Any] = Depends(current_user)) -> UserProtocol[Any]:
    """Return the current user if active, otherwise 403."""
    if not user.is_active:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user")
    return user


async def current_verified_user(user: UserProtocol[Any] = Depends(current_active_user)) -> UserProtocol[Any]:
    """Return the current user if active and verified, otherwise 403."""
    if not user.is_verified:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User not verified")
    return user
