const { kiemtraApiParams, layThongtinUser } = require('../config/kthc');

// API validation middleware
function kiemtraApiMiddleware(req, res, next) {
  const { isApiCall, apiParams } = req.body;
  
  if (isApiCall) {
    try {
      // Validate API parameters
      kiemtraApiParams(apiParams);
      
      // Extract and validate user info
      const userInfo = layThongtinUser(apiParams);
      
      // Add userInfo to request
      req.userInfo = userInfo;
      
      console.log('👤 User Info for API:', userInfo);
      
    } catch (error) {
      return res.status(400).json({
        success: false,
        error: `API validation failed: ${error.message}`
      });
    }
  }
  
  next();
}

// Check if API call middleware
function kiemtraApiCallMiddleware(req, res, next) {
  const { isApiCall } = req.body;
  
  if (isApiCall) {
    console.log('🎯 === XỬ LÝ API CALL ===');
    console.log('📋 Message:', req.body.message);
    console.log('📊 API Params:', req.body.apiParams);
  } else {
    console.log('💬 === XỬ LÝ CHAT THƯỜNG ===');
    console.log('📝 Message:', req.body.message);
  }
  
  next();
}

module.exports = {
  kiemtraApiMiddleware,
  kiemtraApiCallMiddleware
};
