"""
Endpoints del dashboard para estadísticas y métricas empresariales
"""

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from core.database import get_core_db
from core.security import get_current_user, validate_access_to_resource

from .dto import DashboardStats, OperationsOverview, InventoryMetrics
from .service import DashboardService

router = APIRouter(prefix="/dashboard", tags=["Dashboard"])


@router.get("/stats", response_model=DashboardStats)
async def get_dashboard_stats(
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Obtiene estadísticas completas del dashboard para la compañía especificada.

    Incluye:
    - KPIs principales (facturas, pedimentos, clientes, proveedores, items)
    - Gráficas de tendencias (facturas por mes, operaciones por tipo)
    - Top clientes y proveedores
    - Actividad reciente
    """
    # Validar acceso
    tenant_id = validate_access_to_resource(db, company_id, current_user)

    # Generar estadísticas
    service = DashboardService(db, tenant_id, company_id)
    stats = service.get_complete_dashboard_stats()

    return stats


@router.get("/operations-overview", response_model=OperationsOverview)
async def get_operations_overview(
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Obtiene una vista general de las operaciones
    """
    tenant_id = validate_access_to_resource(db, company_id, current_user)

    service = DashboardService(db, tenant_id, company_id)

    # Implementación básica
    ops_by_type = service.get_operations_by_type()

    return OperationsOverview(
        total_operations=sum(int(op.value) for op in ops_by_type),
        by_type={op.label: int(op.value) for op in ops_by_type},
        by_status={},
    )


@router.get("/inventory-metrics", response_model=InventoryMetrics)
async def get_inventory_metrics(
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Obtiene métricas de inventario
    """
    tenant_id = validate_access_to_resource(db, company_id, current_user)

    service = DashboardService(db, tenant_id, company_id)
    items_kpi = service.get_items_metrics()

    return InventoryMetrics(
        total_items=int(items_kpi.value),
        items_in_stock=int(items_kpi.value),  # Simplificado
        items_low_stock=0,
        by_category={},
    )
