# acl/security/permission_required.py
from fastapi import Depends, HTTPException, status
from sqlalchemy.orm import Session

from acl.security.permission_service import permission_service
from acl.security.permission_handler import permission_handler_registry
from acl.security.dependencies import get_current_user_id, get_current_account_id, get_db


def permission_required(required_permission: str):
    """
    FastAPI permission dependency:
       @app.get("/items", dependencies=[Depends(permission_required("READ"))])
    """
    async def checker(
        current_user_id: str = Depends(get_current_user_id),
        current_account_id: str = Depends(get_current_account_id),
        db: Session = Depends(get_db),
    ):

        # Custom handler: "custom:handlerName"
        if required_permission.startswith("custom:"):
            handler_name = required_permission[7:]
            handler = permission_handler_registry.get(handler_name)
            if handler is None:
                raise HTTPException(
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                    detail=f"Custom permission handler '{handler_name}' not registered",
                )
            if not handler.has_permission(authentication=current_user_id):
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN,
                    detail="Forbidden",
                )
            return

        # Standard permission check
        permissions = permission_service.load_user_permissions(
            db=db, user_id=current_user_id, account_id=current_account_id
        )
        names = {p.name for p in permissions}

        if required_permission not in names:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Forbidden",
            )

    return checker
