const express = require('express');
const router = express.Router();
const { taoBaohiem, taoBaohiemvoiCTGSDachon } = require('./baoHiemService');
const { sessionMiddleware, kiemtraSession } = require('../../middleware/sessionMiddleware');
const { kiemtraApiMiddleware, kiemtraApiCallMiddleware } = require('../../middleware/apiMiddleware');

// Route: Tạo bảo hiểm tháng
router.post('/tao-bao-hiem', 
  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 bảo hiểm tháng') {
        return res.status(400).json({
          success: false,
          error: 'Invalid message for insurance creation'
        });
      }
      
      const result = await taoBaohiem(userInfo);
      res.json(result);
      
    } catch (error) {
      console.error('❌ Error in tao-bao-hiem route:', error);
      res.status(500).json({
        success: false,
        error: error.message || 'Internal server error'
      });
    }
  }
);

// Route: Tạo bảo hiểm với CTGS
router.post('/tao-bao-hiem-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 taoBaohiemvoiCTGSDachon(userInfo, ctgsId, req.sessionId);
      res.json(result);
      
    } catch (error) {
      console.error('❌ Error in tao-bao-hiem-ctgs route:', error);
      res.status(500).json({
        success: false,
        error: error.message || 'Internal server error'
      });
    }
  }
);

module.exports = router;
