from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session

from app.core.security import decode_access_token
from app.db.session import get_db
from app.models import AdminUser

bearer_scheme = HTTPBearer(auto_error=False)

ROLE_ALIASES = {
    "admin": "system_admin",
}


def get_current_admin(
    credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
    db: Session = Depends(get_db),
) -> AdminUser:
    if credentials is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
    payload = decode_access_token(credentials.credentials)
    if not payload:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
    admin = db.get(AdminUser, int(payload["sub"]))
    if not admin or admin.status != "active":
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Inactive user")
    return admin


def require_roles(*role_codes: str):
    def checker(admin: AdminUser = Depends(get_current_admin)) -> AdminUser:
        role_code = ROLE_ALIASES.get(admin.role_code, admin.role_code)
        if role_code not in role_codes:
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Permission denied")
        return admin

    return checker
