const { ChatSessionService } = require('../services/databaseService');

// Session middleware
async function sessionMiddleware(req, res, next) {
  try {
    const { sessionId, userInfo, domain, apiMapping } = req.body;
    
        // Tạo user_info object với thông tin từ localStorage
    const userInfoData = {
        user_id: userInfo?.user_id || req.body.userId || 'anonymous',
        domain: domain || req.body.domain || req.headers.origin || 'unknown',
        user: userInfo?.user || req.body.user || '',
        token_httc: userInfo?.token_httc || req.body.token_httc || '',
        kthcMaCoQuan: userInfo?.kthcMaCoQuan || req.body.kthcMaCoQuan || null,
        kthcMaCanBo: userInfo?.kthcMaCanBo || req.body.kthcMaCanBo || null,
        kthcNam: userInfo?.kthcNam || req.body.kthcNam || null,
        kthcThang: userInfo?.kthcThang || req.body.kthcThang || null,
        kthcplgd: userInfo?.kthcplgd || req.body.kthcplgd || '',
        kthcIdvunglv: userInfo?.kthcIdvunglv || req.body.kthcIdvunglv || null,
        kthcNlb: userInfo?.kthcNlb || req.body.kthcNlb || '',
        kthcPtkt: userInfo?.kthcPtkt || req.body.kthcPtkt || '',
        kthcTenCoQuan: userInfo?.kthcTenCoQuan || req.body.kthcTenCoQuan || '',
        kthcMSQHNS: userInfo?.kthcMSQHNS || req.body.kthcMSQHNS || null,
        kthcMaDonvi: userInfo?.kthcMaDonvi || req.body.kthcMaDonvi || '',
        currentContext: userInfo?.currentContext || req.body.currentContext || 'Tạo lương tháng'
    };
    
    // Debug log để kiểm tra user info
    console.log('🔍 Debug Session Middleware - User Info:', {
        userInfo: userInfo,
        userInfoData: userInfoData,
        reqBody: {
            userInfo: req.body.userInfo,
            domain: req.body.domain,
            user: req.body.user
        }
    });
    
    // Auto-create session if not exists
    if (!sessionId) {
      const newSessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      await ChatSessionService.create({
        session_id: newSessionId,
        user_info: userInfoData,
        api_mapping: apiMapping || null,
        last_activity: new Date(),
        is_active: true
      });
      req.sessionId = newSessionId;
      console.log('🆕 Tạo session mới:', newSessionId, 'Domain:', userInfoData.domain, 'User:', userInfoData.user);
    } else {
      req.sessionId = sessionId;
      console.log('🔍 Session ID được sử dụng:', sessionId);
      
      let session = await ChatSessionService.getBySessionId(sessionId);
      
      if (!session) {
        await ChatSessionService.create({
          session_id: sessionId,
          user_info: userInfoData,
          api_mapping: apiMapping || null,
          last_activity: new Date(),
          is_active: true
        });
        console.log('🆕 Tạo session mới cho ID:', sessionId, 'Domain:', userInfoData.domain, 'User:', userInfoData.user);
      } else {
        // Cập nhật thông tin user và thời gian hoạt động
        await ChatSessionService.updateSessionInfo(sessionId, {
          user_info: userInfoData,
          api_mapping: apiMapping || session.api_mapping,
          last_activity: new Date()
        });
        console.log('🔄 Cập nhật session:', sessionId, 'Domain:', userInfoData.domain, 'User:', userInfoData.user);
      }
    }
    
    next();
  } catch (error) {
    console.error('❌ Lỗi trong session middleware:', error);
    next();
  }
}

// Validate session middleware
async function kiemtraSession(req, res, next) {
  try {
    const { sessionId } = req.body;
    
    if (!sessionId) {
      return res.status(400).json({
        success: false,
        error: 'Session ID is required'
      });
    }
    
    const session = await ChatSessionService.getBySessionId(sessionId);
    if (!session) {
      return res.status(404).json({
        success: false,
        error: 'Session not found'
      });
    }
    
    req.session = session;
    next();
  } catch (error) {
    console.error('❌ Lỗi trong kiemtraSession:', error);
    return res.status(500).json({
      success: false,
      error: 'Internal server error'
    });
  }
}

module.exports = {
  sessionMiddleware,
  kiemtraSession
};
