"""
Ejemplo de integración del módulo de permisos en el router principal.
Este archivo muestra cómo incluir las rutas de permisos en tu API.
"""

from fastapi import APIRouter, Depends
from api.v1.modules.core.permissions import router as permissions_router

# Crear el router principal de la API v1
api_v1_router = APIRouter(prefix="/api/v1")

# ============================================================================
# REGISTRAR EL MÓDULO DE PERMISOS
# ============================================================================

# Opción 1: Incluir directamente con el prefix ya definido en el módulo
api_v1_router.include_router(permissions_router)
# Esto creará rutas como: /api/v1/permissions/me, /api/v1/permissions/roles, etc.


# Opción 2: Sobrescribir el prefix si lo necesitas
# api_v1_router.include_router(
#     permissions_router, 
#     prefix="/permisos",  # Cambiar a español si prefieres
#     tags=["Permisos"]
# )


# ============================================================================
# IMPORTAR DEPENDENCIAS PARA USAR EN OTRAS RUTAS
# ============================================================================

from api.v1.modules.core.permissions import (
    RequirePermission,
    PermissionChecker,
    get_current_user_permissions,
    PermissionService
)

# ============================================================================
# EJEMPLO: USAR PERMISOS EN OTROS MÓDULOS
# ============================================================================

# Supongamos que tienes un módulo de facturas
invoices_router = APIRouter(prefix="/invoices", tags=["Invoices"])

@invoices_router.get("/")
async def list_invoices(
    _: None = Depends(RequirePermission("invoice.view"))
):
    """Lista todas las facturas (requiere permiso invoice.view)."""
    return {
        "invoices": [
            {"id": 1, "number": "INV-001", "amount": 1000},
            {"id": 2, "number": "INV-002", "amount": 2000}
        ]
    }


@invoices_router.post("/")
async def create_invoice(
    _: None = Depends(PermissionChecker(["invoice.view", "invoice.create"], require_all=True))
):
    """Crea una factura (requiere invoice.view + invoice.create)."""
    return {"message": "Invoice created", "id": 3}


@invoices_router.delete("/{invoice_id}")
async def delete_invoice(
    invoice_id: int,
    _: None = Depends(RequirePermission("invoice.delete"))
):
    """Elimina una factura (requiere invoice.delete)."""
    return {"message": f"Invoice {invoice_id} deleted"}


# Registrar el router de facturas
api_v1_router.include_router(invoices_router)


# ============================================================================
# EJEMPLO: RUTA CON LÓGICA CONDICIONAL SEGÚN PERMISOS
# ============================================================================

reports_router = APIRouter(prefix="/reports", tags=["Reports"])

@reports_router.get("/dashboard")
async def get_reports_dashboard(
    user_permissions: set = Depends(get_current_user_permissions)
):
    """
    Dashboard de reportes que muestra diferentes secciones según los permisos.
    No requiere permisos específicos, pero el contenido varía.
    """
    sections = []
    
    if "report.financial.view" in user_permissions:
        sections.append({
            "type": "financial",
            "title": "Reportes Financieros",
            "reports": ["Balance General", "Estado de Resultados", "Flujo de Efectivo"]
        })
    
    if "report.admin.view" in user_permissions:
        sections.append({
            "type": "administrative",
            "title": "Reportes Administrativos",
            "reports": ["Actividad de Usuarios", "Auditoría", "Logs del Sistema"]
        })
    
    if "invoice.view" in user_permissions:
        sections.append({
            "type": "invoices",
            "title": "Reportes de Facturación",
            "reports": ["Facturas por Mes", "Facturas Pendientes", "Análisis de Ventas"]
        })
    
    return {
        "user_permissions": list(user_permissions),
        "available_sections": sections
    }


# Registrar el router de reportes
api_v1_router.include_router(reports_router)


# ============================================================================
# EXPORTAR EL ROUTER PRINCIPAL
# ============================================================================

__all__ = ["api_v1_router"]


# ============================================================================
# USO EN main.py
# ============================================================================
"""
En tu backend/main.py, incluye el router así:

from fastapi import FastAPI
from api.v1.integration_example import api_v1_router

app = FastAPI(title="Mi API Multi-Tenant")

# Registrar todas las rutas de API v1
app.include_router(api_v1_router)

# Ahora tendrás:
# - /api/v1/permissions/*  (rutas de permisos)
# - /api/v1/invoices/*     (rutas de facturas protegidas)
# - /api/v1/reports/*      (rutas de reportes)
"""
