const express = require('express');
const router = express.Router();
const { taoLuongvoiCTGS, taoLuongvoiCTGSDachon } = require('./luongService');
const { sessionMiddleware, kiemtraSession } = require('../../middleware/sessionMiddleware');
const { kiemtraApiMiddleware, kiemtraApiCallMiddleware } = require('../../middleware/apiMiddleware');

// Route: Tạo lương tháng
router.post('/tao-luong', 
  sessionMiddleware,
  kiemtraApiMiddleware,
  kiemtraApiCallMiddleware,
  async (req, res) => {
    try {
      const { message, isApiCall, userInfo, sessionId } = req.body;
      
      if (!isApiCall) {
        return res.status(400).json({
          success: false,
          error: 'This endpoint is for API calls only'
        });
      }
      
      if (message !== 'Tạo lương tháng') {
        return res.status(400).json({
          success: false,
          error: 'Invalid message for salary creation'
        });
      }
      
      const result = await taoLuongvoiCTGS(userInfo, sessionId);
      res.json(result);
      
    } catch (error) {
      console.error('❌ Error in tao-luong route:', error);
      res.status(500).json({
        success: false,
        error: error.message || 'Internal server error'
      });
    }
  }
);

// Route: Tạo lương với CTGS được chọn
router.post('/tao-luong-ctgs', 
  sessionMiddleware,
  kiemtraApiMiddleware,
  kiemtraApiCallMiddleware,
  async (req, res) => {
    try {
      const { message, isApiCall, userInfo, sessionId } = req.body;
      
      if (!isApiCall) {
        return res.status(400).json({
          success: false,
          error: 'This endpoint is for API calls only'
        });
      }
      
      // message sẽ là index của CTGS được chọn
      const ctgsIndex = parseInt(message);
      if (isNaN(ctgsIndex)) {
        return res.status(400).json({
          success: false,
          error: 'Invalid CTGS index'
        });
      }
      
      const result = await taoLuongvoiCTGSDachon(userInfo, ctgsIndex, sessionId);
      res.json(result);
      
    } catch (error) {
      console.error('❌ Error in tao-luong-ctgs route:', error);
      res.status(500).json({
        success: false,
        error: error.message || 'Internal server error'
      });
    }
  }
);

module.exports = router;
