# acl/security/permission_service.py
from typing import List
from sqlalchemy import select
from sqlalchemy.orm import Session
from acl.models.permission import Permission
from acl.models.role import IkonRoleMembership, IkonRolePermission


class PermissionService:
    """
    Equivalent to JpaUserDetailsService from Java
    """

    def load_user_permissions(self, db: Session, user_id: str, account_id: str) -> List[Permission]:
        role_ids = [
            r[0] for r in
            db.execute(
                select(IkonRoleMembership.role_id)
                .where(IkonRoleMembership.user_id == user_id,
                       IkonRoleMembership.account_id == account_id)
            ).all()
        ]

        if not role_ids:
            return []

        stmt = (
            select(Permission)
            .join(IkonRolePermission, Permission.id == IkonRolePermission.permission_id)
            .where(IkonRolePermission.role_id.in_(role_ids))
        )
        return [row[0] for row in db.execute(stmt).all()]


permission_service = PermissionService()
