import os
from typing import Optional

from fastapi import Depends, Header, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

from .enums import UserRole
from .schemas import CurrentUser
from .security import verify_token

security = HTTPBearer()


def require_request_id(
    request_id: Optional[str] = Header(None, alias="request-id"),
) -> Optional[str]:
    environment = os.getenv("ENVIRONMENT")
    if environment in ("development", "test"):
        return request_id

    if not request_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Request-Id header is required",
        )
    return request_id


def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    _request_id: str = Depends(require_request_id),
) -> CurrentUser:
    token = credentials.credentials
    payload = verify_token(token)

    aal = payload.get("aal")
    if aal != "aal2":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Forbidden - Multi-factor authentication required",
        )

    app_metadata = payload.get("app_metadata", {})
    role = app_metadata.get("role") or payload.get("role")

    return CurrentUser(
        user_id=payload.get("sub"),
        email=payload.get("email"),
        role=role,
        aal=aal,
        amr=payload.get("amr"),
    )


def get_current_user_id(user: CurrentUser = Depends(get_current_user)) -> str:
    return user.user_id


def require_admin(user: CurrentUser = Depends(get_current_user)) -> CurrentUser:
    if user.role != UserRole.ADMIN:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Forbidden - Requires Admin role",
        )
    return user
