"""FastAPI dependencies for auth: get_current_user, get_verified_user, get_admin_user."""
from __future__ import annotations
from fastapi import Depends, HTTPException, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from .base import User
from .tokens import verify_access_token
from .db import get_user_by_id

_bearer = HTTPBearer(auto_error=False)

async def get_current_user(
    request: Request,
    creds: HTTPAuthorizationCredentials | None = Depends(_bearer),
) -> User:
    if not creds:
        raise HTTPException(status_code=401, detail="Not authenticated")
    payload = verify_access_token(request.app.state.jwt_key, creds.credentials)
    if not payload:
        raise HTTPException(status_code=401, detail="Invalid or expired token")
    user = get_user_by_id(request.app.state.db_path, payload["sub"])
    if not user:
        raise HTTPException(status_code=401, detail="User not found")
    return user

async def get_verified_user(user: User = Depends(get_current_user)) -> User:
    if user.role not in ("user", "admin", "read-only"):
        raise HTTPException(status_code=403, detail="Account pending approval")
    return user

async def get_admin_user(user: User = Depends(get_current_user)) -> User:
    if user.role != "admin":
        raise HTTPException(status_code=403, detail="Admin access required")
    return user
