/**
 * Dashboard Controller
 * Handles dashboard statistics and data
 */

const { query } = require("../config/database");
const Task = require("../models/Task");
const Employee = require("../models/Employee");
const ActivityLog = require("../models/ActivityLog");

/**
 * Get admin dashboard statistics
 * GET /api/dashboard/admin
 */
const getAdminDashboard = async (req, res, next) => {
  try {
    // Get overall statistics
    const [dashboardStats] = await query("CALL sp_get_dashboard_stats()");
    const stats = dashboardStats[0];

    // Get recent activities
    const recentActivities = await ActivityLog.getRecent(10);

    // Get overdue tasks
    const overdueTasks = await Task.getOverdueTasks(5);

    // Get task distribution by department
    const tasksByDepartment = await query(`
            SELECT d.name as department, COUNT(t.id) as task_count
            FROM departments d
            LEFT JOIN tasks t ON d.id = t.department_id AND t.is_deleted = FALSE
            WHERE d.is_active = TRUE
            GROUP BY d.id, d.name
            ORDER BY task_count DESC
        `);

    // Get task completion rate by month (last 6 months)
    const taskTrend = await query(`
            SELECT 
                DATE_FORMAT(created_at, '%Y-%m') as month,
                COUNT(*) as total,
                SUM(CASE WHEN status = 'Completed' THEN 1 ELSE 0 END) as completed
            FROM tasks
            WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
                  AND is_deleted = FALSE
            GROUP BY DATE_FORMAT(created_at, '%Y-%m')
            ORDER BY month ASC
        `);

    // Get task distribution by priority
    const tasksByPriority = await query(`
            SELECT priority, COUNT(*) as count
            FROM tasks
            WHERE is_deleted = FALSE
            GROUP BY priority
        `);

    // Get top performers (employees with most completed tasks)
    const topPerformers = await query(`
            SELECT 
                e.id,
                CONCAT(e.first_name, ' ', e.last_name) as name,
                e.job_title,
                d.name as department,
                COUNT(t.id) as completed_tasks
            FROM employees e
            LEFT JOIN departments d ON e.department_id = d.id
            INNER JOIN tasks t ON e.id = t.assigned_to 
                AND t.status = 'Completed' 
                AND t.is_deleted = FALSE
            WHERE e.is_deleted = FALSE
            GROUP BY e.id, e.first_name, e.last_name, e.job_title, d.name
            ORDER BY completed_tasks DESC
            LIMIT 5
        `);

    res.json({
      success: true,
      data: {
        stats,
        recentActivities,
        overdueTasks,
        tasksByDepartment,
        taskTrend,
        tasksByPriority,
        topPerformers,
      },
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get employee dashboard data
 * GET /api/dashboard/employee
 */
const getEmployeeDashboard = async (req, res, next) => {
  try {
    const employeeId = req.user.employeeId;

    // Get task statistics for employee
    const taskStats = await Task.getStatistics(employeeId);

    // Get my tasks
    const myTasks = await Task.findByEmployee(employeeId, { limit: 10 });

    // Get upcoming deadlines
    const upcomingDeadlines = await Task.getUpcomingDeadlines(7, employeeId);

    // Get recent task updates
    const recentUpdates = await query(
      `
            SELECT t.*, 
                   CONCAT(ab.first_name, ' ', ab.last_name) as assigned_by_name
            FROM tasks t
            LEFT JOIN employees ab ON t.assigned_by = ab.id
            WHERE t.assigned_to = ? AND t.is_deleted = FALSE
            ORDER BY t.updated_at DESC
            LIMIT 5
        `,
      [employeeId],
    );

    res.json({
      success: true,
      data: {
        stats: taskStats,
        myTasks,
        upcomingDeadlines,
        recentUpdates,
      },
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get manager dashboard data
 * GET /api/dashboard/manager
 */
const getManagerDashboard = async (req, res, next) => {
  try {
    const departmentId = req.user.departmentId;

    // Get department statistics
    const deptStats = await query(
      `
            SELECT 
                COUNT(DISTINCT e.id) as total_employees,
                COUNT(t.id) as total_tasks,
                SUM(CASE WHEN t.status = 'Pending' THEN 1 ELSE 0 END) as pending_tasks,
                SUM(CASE WHEN t.status = 'Completed' THEN 1 ELSE 0 END) as completed_tasks,
                SUM(CASE WHEN t.due_date < CURDATE() AND t.status != 'Completed' THEN 1 ELSE 0 END) as overdue_tasks
            FROM departments d
            LEFT JOIN employees e ON d.id = e.department_id AND e.is_deleted = FALSE
            LEFT JOIN tasks t ON d.id = t.department_id AND t.is_deleted = FALSE
            WHERE d.id = ?
        `,
      [departmentId],
    );

    // Get team members with their task counts
    const teamMembers = await query(
      `
            SELECT 
                e.id,
                e.employee_id,
                CONCAT(e.first_name, ' ', e.last_name) as name,
                e.job_title,
                COUNT(t.id) as total_tasks,
                SUM(CASE WHEN t.status = 'Pending' THEN 1 ELSE 0 END) as pending,
                SUM(CASE WHEN t.status = 'In Progress' THEN 1 ELSE 0 END) as in_progress,
                SUM(CASE WHEN t.status = 'Completed' THEN 1 ELSE 0 END) as completed
            FROM employees e
            LEFT JOIN tasks t ON e.id = t.assigned_to AND t.is_deleted = FALSE
            WHERE e.department_id = ? AND e.is_deleted = FALSE AND e.status = 'Active'
            GROUP BY e.id, e.employee_id, e.first_name, e.last_name, e.job_title
        `,
      [departmentId],
    );

    // Get department tasks
    const deptTasks = await query(
      `
            SELECT t.*,
                   CONCAT(ae.first_name, ' ', ae.last_name) as assigned_to_name
            FROM tasks t
            LEFT JOIN employees ae ON t.assigned_to = ae.id
            WHERE t.department_id = ? AND t.is_deleted = FALSE
            ORDER BY 
                CASE t.status 
                    WHEN 'In Progress' THEN 1 
                    WHEN 'Pending' THEN 2 
                    WHEN 'On Hold' THEN 3 
                    WHEN 'Completed' THEN 4 
                END,
                t.due_date ASC
            LIMIT 20
        `,
      [departmentId],
    );

    res.json({
      success: true,
      data: {
        stats: deptStats[0],
        teamMembers,
        tasks: deptTasks,
      },
    });
  } catch (error) {
    next(error);
  }
};

module.exports = {
  getAdminDashboard,
  getEmployeeDashboard,
  getManagerDashboard,
};
