from __future__ import annotations
from typing import Annotated

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from sqlalchemy.orm import Session

from app.core.config import settings
from app.db.session import get_db
from app.models.enums import Role
from app.models.user import User

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
FUNCTIONALITY_KEYS = {"dashboard", "requisitions", "financial_management", "procurement", "tendering", "reports"}


def has_functionality_access(user: User, functionality: str) -> bool:
    if user.role == Role.admin:
        return True
    if user.functionality_access is None:
        return functionality in FUNCTIONALITY_KEYS
    return functionality in user.functionality_access


def get_current_user(token: Annotated[str, Depends(oauth2_scheme)], db: Annotated[Session, Depends(get_db)]) -> User:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        username: str | None = payload.get("sub")
        if username is None:
            raise credentials_exception
    except JWTError as exc:
        raise credentials_exception from exc
    user = db.query(User).filter(User.username == username).first()
    if not user or not user.is_active:
        raise credentials_exception
    return user


def require_roles(*roles: Role):
    def checker(current_user: Annotated[User, Depends(get_current_user)]) -> User:
        if current_user.role not in roles and current_user.role != Role.admin:
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Insufficient permissions")
        return current_user

    return checker


def require_access(*functionalities: str):
    def checker(current_user: Annotated[User, Depends(get_current_user)]) -> User:
        if not any(has_functionality_access(current_user, item) for item in functionalities):
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Functionality access denied")
        return current_user

    return checker


def stage_functionality(stage: str) -> str:
    if stage == "requisitions":
        return "requisitions"
    if stage in {
        "procurement-cases",
        "gem-cases",
        "e-tender-cases",
        "global-tender-cases",
        "lpc-cases",
        "open-market-cases",
        "other-procurement-cases",
    }:
        return "procurement"
    return "tendering"


def require_stage_access(
    stage: str,
    current_user: Annotated[User, Depends(get_current_user)],
) -> User:
    if not has_functionality_access(current_user, stage_functionality(stage)):
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Functionality access denied")
    return current_user
