const prisma = require("../models/prisma");
const logger = require("../utils/logger");

const getGlobalKPIs = async (req, res) => {
  try {
    const [
      totalProjects,
      projectsByStatus,
      recentProjects,
      totalTasks,
      tasksByStatus,
      totalUsers,
    ] = await Promise.all([
      prisma.project.count(),
      prisma.project.groupBy({ by: ["status"], _count: true }),
      prisma.project.findMany({
        take: 5,
        orderBy: { createdAt: "desc" },
        select: { id: true, name: true, code: true, status: true, ragStatus: true, progressPct: true, budget: true, priority: true },
      }),
      prisma.task.count(),
      prisma.task.groupBy({ by: ["status"], _count: true }),
      prisma.user.count({ where: { isActive: true } }),
    ]);

    const statusMap = {};
    projectsByStatus.forEach((s) => { statusMap[s.status] = s._count; });

    const taskStatusMap = {};
    tasksByStatus.forEach((s) => { taskStatusMap[s.status] = s._count; });

    res.json({
      projects: {
        total: totalProjects,
        active: statusMap["ACTIVO"] || 0,
        paused: statusMap["PAUSADO"] || 0,
        completed: statusMap["COMPLETADO"] || 0,
        atRisk: statusMap["EN_RIESGO"] || 0,
        cancelled: statusMap["CANCELADO"] || 0,
      },
      tasks: {
        total: totalTasks,
        pending: taskStatusMap["PENDIENTE"] || 0,
        inProgress: taskStatusMap["EN_PROCESO"] || 0,
        blocked: taskStatusMap["BLOQUEADA"] || 0,
        completed: taskStatusMap["COMPLETADA"] || 0,
      },
      users: { active: totalUsers },
      recentProjects,
    });
  } catch (error) {
    logger.error("Error obteniendo KPIs globales:", error);
    res.status(500).json({ error: "Error obteniendo KPIs" });
  }
};

module.exports = { getGlobalKPIs };
