"""Permission template routes — CRUD API for reusable permission presets.""" from __future__ import annotations import uuid from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.ext.asyncio import AsyncSession from app.core.db import get_db from app.deps import get_current_user, require_permission from app.schemas.permission_template import ( PermissionTemplateCreate, PermissionTemplateUpdate, PermissionTemplateApply, ) from app.services import permission_template_service router = APIRouter(prefix="/api/v1/permission-templates", tags=["permission-templates"]) @router.get("") async def list_templates( entity_type: str | None = None, db: AsyncSession = Depends(get_db), current_user: dict = Depends(require_permission("permissions:templates:read")), ): """List all permission templates for the current tenant.""" tenant_id = uuid.UUID(current_user["tenant_id"]) items = await permission_template_service.list_templates(db, tenant_id, entity_type) return {"items": items, "total": len(items)} @router.post("", status_code=status.HTTP_201_CREATED) async def create_template( body: PermissionTemplateCreate, db: AsyncSession = Depends(get_db), current_user: dict = Depends(require_permission("permissions:templates:write")), ): """Create a new permission template.""" tenant_id = uuid.UUID(current_user["tenant_id"]) try: return await permission_template_service.create_template( db, tenant_id, name=body.name, entity_type=body.entity_type, level=body.level, trigger_condition=body.trigger_condition, auto_share_with=body.auto_share_with, ) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) @router.put("/{template_id}") async def update_template( template_id: str, body: PermissionTemplateUpdate, db: AsyncSession = Depends(get_db), current_user: dict = Depends(require_permission("permissions:templates:write")), ): """Update an existing permission template.""" tenant_id = uuid.UUID(current_user["tenant_id"]) try: return await permission_template_service.update_template( db, tenant_id, template_id, name=body.name, entity_type=body.entity_type, level=body.level, trigger_condition=body.trigger_condition, auto_share_with=body.auto_share_with, ) except ValueError as e: raise HTTPException(status_code=404, detail=str(e)) @router.delete("/{template_id}", status_code=status.HTTP_204_NO_CONTENT) async def delete_template( template_id: str, db: AsyncSession = Depends(get_db), current_user: dict = Depends(require_permission("permissions:templates:write")), ): """Delete a permission template.""" tenant_id = uuid.UUID(current_user["tenant_id"]) try: await permission_template_service.delete_template(db, tenant_id, template_id) except ValueError as e: raise HTTPException(status_code=404, detail=str(e)) @router.post("/apply", status_code=status.HTTP_201_CREATED) async def apply_template( body: PermissionTemplateApply, db: AsyncSession = Depends(get_db), current_user: dict = Depends(require_permission("permissions:templates:write")), ): """Apply a permission template to an entity, creating entity_permissions.""" tenant_id = uuid.UUID(current_user["tenant_id"]) user_id = uuid.UUID(current_user["user_id"]) try: result = await permission_template_service.apply_template( db, tenant_id, body.entity_type, body.entity_id, template_id=body.template_id, created_by=user_id, ) return {"applied": result, "count": len(result)} except ValueError as e: raise HTTPException(status_code=400, detail=str(e))