const express = require('express');
const router = express.Router();
const { taoCongdoan, taoCongdoanvoiCTGS } = require('./congDoanService');
const { sessionMiddleware, kiemtraSession } = require('../../middleware/sessionMiddleware');
const { kiemtraApiMiddleware, kiemtraApiCallMiddleware } = require('../../middleware/apiMiddleware');

// Route: Tạo kinh phí công đoàn tháng
router.post('/tao-cong-doan', 
  sessionMiddleware,
  kiemtraApiMiddleware,
  kiemtraApiCallMiddleware,
  async (req, res) => {
    try {
      const { message, isApiCall, userInfo } = req.body;
      
      if (!isApiCall) {
        return res.status(400).json({
          success: false,
          error: 'This endpoint is for API calls only'
        });
      }
      
      if (message !== 'Tạo kinh phí công đoàn tháng') {
        return res.status(400).json({
          success: false,
          error: 'Invalid message for union creation'
        });
      }
      
      const result = await taoCongdoan(userInfo);
      res.json(result);
      
    } catch (error) {
      console.error('❌ Error in tao-cong-doan route:', error);
      res.status(500).json({
        success: false,
        error: error.message || 'Internal server error'
      });
    }
  }
);

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

module.exports = router;
