const vacationDashboardModel = require('../models/vacationDashboardModel');

const vacationDashboardController = {
  async getDashboard(req, res) {
    try {
      const year = parseInt(req.query.year) || new Date().getFullYear();
      const filters = {
        department_id: req.query.department_id || null,
        search_name: req.query.search_name || null
      };

      const [summary, rows] = await Promise.all([
        vacationDashboardModel.getSummary(year),
        vacationDashboardModel.getEmployeeList(year, filters)
      ]);

      // user_id별 그룹핑
      const employeeMap = {};
      rows.forEach(row => {
        if (!employeeMap[row.user_id]) {
          employeeMap[row.user_id] = {
            user_id: row.user_id,
            name: row.name,
            username: row.username,
            department_name: row.department_name,
            hire_date: row.hire_date,
            balances: []
          };
        }
        if (row.id) {
          employeeMap[row.user_id].balances.push({
            balance_type: row.balance_type,
            type_name: row.type_name,
            type_code: row.type_code,
            total_days: row.total_days,
            used_days: row.used_days,
            remaining_days: row.remaining_days,
            expires_at: row.expires_at
          });
        }
      });
      const employees = Object.values(employeeMap);

      res.json({ success: true, data: { summary, employees } });
    } catch (error) {
      console.error('휴가 대시보드 조회 오류:', error);
      res.status(500).json({ success: false, error: '서버 오류가 발생했습니다' });
    }
  },

  async getYearlyOverview(req, res) {
    try {
      const year = parseInt(req.query.year) || new Date().getFullYear();
      const [users, balances, companyDeductions] = await Promise.all([
        vacationDashboardModel.getYearlyOverview(year),
        vacationDashboardModel.getBalances(year),
        vacationDashboardModel.getCompanyDeductions(year)
      ]);
      res.json({ success: true, data: { users, balances, companyDeductions } });
    } catch (error) {
      console.error('연간 총괄 조회 오류:', error);
      res.status(500).json({ success: false, error: '서버 오류가 발생했습니다' });
    }
  },

  async getMonthlyDetail(req, res) {
    try {
      const year = parseInt(req.query.year) || new Date().getFullYear();
      const month = parseInt(req.query.month);
      const departmentId = parseInt(req.query.department_id) || 0;
      if (!month || month < 1 || month > 12) {
        return res.status(400).json({ success: false, error: '유효하지 않은 월입니다' });
      }
      const [records, holidays] = await Promise.all([
        vacationDashboardModel.getMonthlyDetail(year, month, departmentId),
        vacationDashboardModel.getHolidays(year, month)
      ]);
      res.json({ success: true, data: { records, holidays } });
    } catch (error) {
      console.error('월간 상세 조회 오류:', error);
      res.status(500).json({ success: false, error: '서버 오류가 발생했습니다' });
    }
  }
};

module.exports = vacationDashboardController;
