"""
Permission API routes.
"""
from typing import Dict, List
from fastapi import APIRouter, Depends
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.deps import get_db, get_current_user
from app.core.response import success_response
from app.models.user import Permission

router = APIRouter()


def _permission_to_dict(permission: Permission) -> Dict:
    return {
        "id": permission.id,
        "permission_name": permission.permission_name,
        "permission_code": permission.permission_code,
        "module": permission.module,
        "module_name": permission.module,
        "resource": permission.resource,
        "action": permission.action,
        "description": permission.description,
        "created_at": permission.created_at,
    }


@router.get("/tree")
async def permission_tree(
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
):
    result = await db.execute(select(Permission).order_by(Permission.module, Permission.id))
    permissions = list(result.scalars().all())

    module_map: Dict[str, List[Permission]] = {}
    module_order: List[str] = []
    for permission in permissions:
        module = permission.module or "misc"
        if module not in module_map:
            module_map[module] = []
            module_order.append(module)
        module_map[module].append(permission)

    tree = []
    for idx, module in enumerate(module_order, start=1):
        children = [_permission_to_dict(p) for p in module_map[module]]
        tree.append(
            {
                "id": -idx,
                "permission_name": module,
                "module_name": module,
                "disabled": True,
                "children": children,
            }
        )

    return success_response(data=tree)
