from __future__ import annotations

from fastapi import HTTPException
from sqlalchemy.orm import Session

from app.modules.core.iam.models import User
from app.modules.core.rbac.deps import get_user_permissions, get_user_roles
from app.modules.core.rbac.permissions_registry import expand_permission_codes


def has_permission(db: Session, user: User | None, permission_code: str) -> bool:
    if not user:
        return False
    roles = set(get_user_roles(db, user.id))
    if "System Admin" in roles:
        return True
    granted = set(get_user_permissions(db, user.id))
    for code in expand_permission_codes(permission_code):
        if code in granted:
            return True
    return False


def require_permission(db: Session, user: User | None, permission_code: str) -> None:
    if not has_permission(db, user, permission_code):
        raise HTTPException(status_code=403, detail=f"Missing permission: {permission_code}")
