/**
 * Conversation Transfer Controller - ROBUST VERSION
 * Handles conversation transfers between admin, stores, departments, and users
 * Supports both WhatsApp Cloud and WhatsApp Web (Evolution API) conversations
 * 
 * Features:
 * - Transfer from admin to store/department/user
 * - Transfer from store to department/user
 * - Transfer from department to user
 * - Transfer between users
 * - Automatic claim release on transfer
 * - Transfer history tracking
 * - Real-time Socket.IO notifications
 * - Full i18n support
 * 
 * @module controllers/ConversationTransferController
 */

const { pool } = require('../config/database');
const { logger } = require('../config/logger');
const { asyncHandler } = require('../middleware/errorHandler');

class ConversationTransferController {
  /**
   * Transfer conversation - UNIFIED ROBUST VERSION
   * Works for both conversations (Evolution API) and whatsapp_cloud_conversations tables
   * POST /api/user/conversations/:id/transfer
   * POST /api/user/whatsapp-cloud/conversations/:id/transfer
   */
  static transferConversation = asyncHandler(async (req, res) => {
    const connection = await pool.getConnection();
    
    try {
      await connection.beginTransaction();
      
      const conversationId = req.params.id;
      const userId = req.user.id;
      const tenantId = req.user.tenantId || req.tenantId;
      const { 
        targetType,      // 'store', 'department', 'user'
        targetId,        // ID or name of target
        targetName,      // Name of target (for backward compatibility)
        reason,          // Optional transfer reason
        source = 'whatsapp_cloud',  // 'whatsapp_cloud' or 'whatsapp_web'
        // Legacy support for old API format
        newUserId,
        newStoreId,
        newDepartmentId
      } = req.body;

      logger.info('🔄 TRANSFER CONVERSATION REQUEST - DETAILED LOG', {
        conversationId,
        userId,
        userName: req.user.name,
        tenantId,
        requestBody: req.body,
        targetType,
        targetId,
        targetName,
        source,
        legacyParams: { newUserId, newStoreId, newDepartmentId }
      });

      // Handle legacy API format
      let finalTargetType = targetType;
      let finalTargetId = targetId;
      let finalTargetName = targetName;

      if (!finalTargetType && (newUserId || newStoreId || newDepartmentId)) {
        logger.info('🔄 Converting legacy API format to new format');
        if (newUserId) {
          finalTargetType = 'user';
          finalTargetId = newUserId;
        } else if (newStoreId) {
          finalTargetType = 'store';
          finalTargetId = newStoreId;
        } else if (newDepartmentId) {
          finalTargetType = 'department';
          finalTargetId = newDepartmentId;
        }
        logger.info('✅ Legacy format converted', { finalTargetType, finalTargetId });
      }

      // Auto-detect source if not provided
      let finalSource = source;
      if (!finalSource || finalSource === 'whatsapp_cloud') {
        // Check if conversation exists in conversations table (Evolution)
        logger.info('🔍 Auto-detecting conversation source');
        const [evolutionCheck] = await connection.execute(
          'SELECT id FROM conversations WHERE id = ? AND tenant_id = ? LIMIT 1',
          [conversationId, tenantId]
        );
        
        if (evolutionCheck.length > 0) {
          finalSource = 'whatsapp_web';
          logger.info('✅ Auto-detected source: whatsapp_web (Evolution API)');
        } else {
          finalSource = 'whatsapp_cloud';
          logger.info('✅ Auto-detected source: whatsapp_cloud');
        }
      } else {
        logger.info('✅ Source provided in request:', finalSource);
      }

      // Validation
      if (!finalTargetType || (!finalTargetId && !finalTargetName)) {
        logger.error('❌ TRANSFER VALIDATION FAILED - Missing target', {
          finalTargetType,
          finalTargetId,
          finalTargetName,
          requestBody: req.body
        });
        await connection.rollback();
        return res.status(400).json({
          success: false,
          message: 'Transfer target type and ID/name are required',
          error: 'MISSING_TRANSFER_TARGET'
        });
      }

      if (!['store', 'department', 'user'].includes(finalTargetType)) {
        logger.error('❌ TRANSFER VALIDATION FAILED - Invalid target type', {
          finalTargetType,
          validTypes: ['store', 'department', 'user']
        });
        await connection.rollback();
        return res.status(400).json({
          success: false,
          message: 'Invalid target type. Must be: store, department, or user',
          error: 'INVALID_TARGET_TYPE'
        });
      }

      logger.info('✅ Transfer validation passed', {
        conversationId,
        userId,
        tenantId,
        finalTargetType,
        finalTargetId,
        finalTargetName,
        finalSource
      });

      // Determine which table to use
      const tableName = finalSource === 'whatsapp_web' ? 'conversations' : 'whatsapp_cloud_conversations';
      const phoneField = finalSource === 'whatsapp_web' ? 'phone_number' : 'contact_phone';

      logger.info('🔍 Determining conversation source', {
        finalSource,
        tableName,
        phoneField,
        conversationId,
        tenantId
      });

      // Get conversation with lock
      logger.info('🔒 Acquiring conversation lock', {
        tableName,
        conversationId,
        tenantId
      });

      const [conversations] = await connection.execute(
        `SELECT * FROM ${tableName} WHERE id = ? AND tenant_id = ? FOR UPDATE`,
        [conversationId, tenantId]
      );

      logger.info('📊 Conversation query result', {
        found: conversations.length > 0,
        conversationCount: conversations.length,
        conversationData: conversations.length > 0 ? {
          id: conversations[0].id,
          phone: conversations[0][phoneField],
          status: conversations[0].status,
          assigned_user_id: conversations[0].assigned_user_id,
          claimed_by_user_id: conversations[0].claimed_by_user_id,
          transferred_to_store: conversations[0].transferred_to_store,
          transferred_to_department: conversations[0].transferred_to_department
        } : null
      });

      if (conversations.length === 0) {
        logger.error('❌ CONVERSATION NOT FOUND', {
          conversationId,
          tenantId,
          tableName,
          source
        });
        await connection.rollback();
        return res.status(404).json({
          success: false,
          message: 'Conversation not found',
          error: 'CONVERSATION_NOT_FOUND'
        });
      }

      const conversation = conversations[0];

      logger.info('✅ Conversation found and locked', {
        conversationId,
        conversationPhone: conversation[phoneField],
        conversationStatus: conversation.status
      });

      // Resolve target based on type
      let resolvedTargetId = finalTargetId;
      let resolvedTargetName = finalTargetName;
      let targetUserId = null;

      logger.info('🎯 Resolving transfer target', {
        finalTargetType,
        resolvedTargetId,
        resolvedTargetName
      });

      if (finalTargetType === 'store') {
        logger.info('🏪 Resolving STORE target', {
          resolvedTargetId,
          resolvedTargetName,
          tenantId
        });

        // Resolve store
        if (!resolvedTargetId && resolvedTargetName) {
          logger.info('🔍 Looking up store by name', { storeName: resolvedTargetName });
          const [stores] = await connection.execute(
            `SELECT id, name FROM stores WHERE tenant_id = ? AND name = ? LIMIT 1`,
            [tenantId, resolvedTargetName]
          );
          logger.info('📊 Store lookup by name result', {
            found: stores.length > 0,
            storeData: stores.length > 0 ? stores[0] : null
          });
          if (stores.length > 0) {
            resolvedTargetId = stores[0].id;
            resolvedTargetName = stores[0].name;
          }
        } else if (resolvedTargetId) {
          logger.info('🔍 Looking up store by ID', { storeId: resolvedTargetId });
          const [stores] = await connection.execute(
            `SELECT id, name FROM stores WHERE tenant_id = ? AND id = ? LIMIT 1`,
            [tenantId, resolvedTargetId]
          );
          logger.info('📊 Store lookup by ID result', {
            found: stores.length > 0,
            storeData: stores.length > 0 ? stores[0] : null
          });
          if (stores.length > 0) {
            resolvedTargetName = stores[0].name;
          }
        }

        if (!resolvedTargetId) {
          logger.error('❌ STORE NOT FOUND', {
            originalTargetId: finalTargetId,
            originalTargetName: finalTargetName,
            tenantId
          });
          await connection.rollback();
          return res.status(404).json({
            success: false,
            message: 'Target store not found',
            error: 'STORE_NOT_FOUND'
          });
        }

        logger.info('✅ Store resolved successfully', {
          storeId: resolvedTargetId,
          storeName: resolvedTargetName
        });
      } else if (finalTargetType === 'department') {
        logger.info('🏢 Resolving DEPARTMENT target', {
          resolvedTargetId,
          resolvedTargetName,
          tenantId
        });

        // Resolve department
        if (!resolvedTargetId && resolvedTargetName) {
          logger.info('🔍 Looking up department by name', { departmentName: resolvedTargetName });
          const [departments] = await connection.execute(
            `SELECT id, name FROM departments WHERE tenant_id = ? AND name = ? LIMIT 1`,
            [tenantId, resolvedTargetName]
          );
          logger.info('📊 Department lookup by name result', {
            found: departments.length > 0,
            departmentData: departments.length > 0 ? departments[0] : null
          });
          if (departments.length > 0) {
            resolvedTargetId = departments[0].id;
            resolvedTargetName = departments[0].name;
          }
        } else if (resolvedTargetId) {
          logger.info('🔍 Looking up department by ID', { departmentId: resolvedTargetId });
          const [departments] = await connection.execute(
            `SELECT id, name FROM departments WHERE tenant_id = ? AND id = ? LIMIT 1`,
            [tenantId, resolvedTargetId]
          );
          logger.info('📊 Department lookup by ID result', {
            found: departments.length > 0,
            departmentData: departments.length > 0 ? departments[0] : null
          });
          if (departments.length > 0) {
            resolvedTargetName = departments[0].name;
          }
        }

        if (!resolvedTargetId) {
          logger.error('❌ DEPARTMENT NOT FOUND', {
            originalTargetId: finalTargetId,
            originalTargetName: finalTargetName,
            tenantId
          });
          await connection.rollback();
          return res.status(404).json({
            success: false,
            message: 'Target department not found',
            error: 'DEPARTMENT_NOT_FOUND'
          });
        }

        logger.info('✅ Department resolved successfully', {
          departmentId: resolvedTargetId,
          departmentName: resolvedTargetName
        });
      } else if (finalTargetType === 'user') {
        logger.info('👤 Resolving USER target', {
          resolvedTargetId,
          tenantId
        });

        // Resolve user
        targetUserId = resolvedTargetId;
        logger.info('🔍 Looking up user by ID', { userId: targetUserId });
        const [users] = await connection.execute(
          `SELECT id, name, store_id, department_id FROM users WHERE tenant_id = ? AND id = ? AND active = 1 LIMIT 1`,
          [tenantId, targetUserId]
        );
        
        logger.info('📊 User lookup result', {
          found: users.length > 0,
          userData: users.length > 0 ? {
            id: users[0].id,
            name: users[0].name,
            store_id: users[0].store_id,
            department_id: users[0].department_id
          } : null
        });

        if (users.length === 0) {
          logger.error('❌ USER NOT FOUND OR INACTIVE', {
            targetUserId,
            tenantId
          });
          await connection.rollback();
          return res.status(404).json({
            success: false,
            message: 'Target user not found or inactive',
            error: 'USER_NOT_FOUND'
          });
        }

        resolvedTargetName = users[0].name;
        
        logger.info('✅ User resolved successfully', {
          userId: targetUserId,
          userName: resolvedTargetName,
          userStoreId: users[0].store_id,
          userDepartmentId: users[0].department_id
        });

        // When transferring to user, also set their store/department
        if (users[0].store_id) {
          logger.info('🔍 Looking up user\'s store', { storeId: users[0].store_id });
          const [stores] = await connection.execute(
            `SELECT id, name FROM stores WHERE id = ? LIMIT 1`,
            [users[0].store_id]
          );
          if (stores.length > 0) {
            resolvedTargetId = stores[0].id;
            logger.info('✅ User\'s store found', {
              storeId: stores[0].id,
              storeName: stores[0].name
            });
          }
        } else if (users[0].department_id) {
          logger.info('🔍 Looking up user\'s department', { departmentId: users[0].department_id });
          const [departments] = await connection.execute(
            `SELECT id, name FROM departments WHERE id = ? LIMIT 1`,
            [users[0].department_id]
          );
          if (departments.length > 0) {
            resolvedTargetId = departments[0].id;
            logger.info('✅ User\'s department found', {
              departmentId: departments[0].id,
              departmentName: departments[0].name
            });
          }
        }
      }

      // Build update query based on target type
      let updateQuery = '';
      let updateParams = [];

      logger.info('🔨 Building UPDATE query', {
        finalTargetType,
        source,
        tableName,
        resolvedTargetId,
        resolvedTargetName,
        targetUserId
      });

      if (finalTargetType === 'store') {
        if (finalSource === 'whatsapp_web') {
          logger.info('📝 Building Evolution (whatsapp_web) STORE transfer query');
          updateQuery = `
            UPDATE ${tableName}
            SET 
              transferred_to_store = ?,
              transferred_to_department = NULL,
              transferred_at = NOW(),
              transferred_by_user_id = ?,
              assigned_user_id = NULL,
              claimed_at = NULL,
              is_claimed = FALSE,
              status = 'waiting',
              updated_at = NOW()
            WHERE id = ? AND tenant_id = ?
          `;
          updateParams = [resolvedTargetName, userId, conversationId, tenantId];
          logger.info('✅ Evolution STORE query built', {
            transferredToStore: resolvedTargetName,
            transferredByUserId: userId,
            conversationId,
            tenantId
          });
        } else {
          logger.info('📝 Building WhatsApp Cloud STORE transfer query');
          updateQuery = `
            UPDATE ${tableName}
            SET 
              transferred_to_store = ?,
              transferred_to_department = NULL,
              transferred_at = NOW(),
              transferred_by_user_id = ?,
              claimed_by_user_id = NULL,
              claimed_at = NULL,
              store_id = ?,
              department_id = NULL,
              status = 'open',
              updated_at = NOW()
            WHERE id = ? AND tenant_id = ?
          `;
          updateParams = [resolvedTargetId, userId, resolvedTargetId, conversationId, tenantId];
          logger.info('✅ WhatsApp Cloud STORE query built', {
            transferredToStore: resolvedTargetId,
            storeId: resolvedTargetId,
            transferredByUserId: userId,
            conversationId,
            tenantId
          });
        }
      } else if (finalTargetType === 'department') {
        if (finalSource === 'whatsapp_web') {
          logger.info('📝 Building Evolution (whatsapp_web) DEPARTMENT transfer query');
          updateQuery = `
            UPDATE ${tableName}
            SET 
              transferred_to_store = NULL,
              transferred_to_department = ?,
              transferred_at = NOW(),
              transferred_by_user_id = ?,
              assigned_user_id = NULL,
              claimed_at = NULL,
              is_claimed = FALSE,
              status = 'waiting',
              updated_at = NOW()
            WHERE id = ? AND tenant_id = ?
          `;
          updateParams = [resolvedTargetName, userId, conversationId, tenantId];
          logger.info('✅ Evolution DEPARTMENT query built', {
            transferredToDepartment: resolvedTargetName,
            transferredByUserId: userId,
            conversationId,
            tenantId
          });
        } else {
          logger.info('📝 Building WhatsApp Cloud DEPARTMENT transfer query');
          updateQuery = `
            UPDATE ${tableName}
            SET 
              transferred_to_store = NULL,
              transferred_to_department = ?,
              transferred_at = NOW(),
              transferred_by_user_id = ?,
              claimed_by_user_id = NULL,
              claimed_at = NULL,
              store_id = NULL,
              department_id = ?,
              status = 'open',
              updated_at = NOW()
            WHERE id = ? AND tenant_id = ?
          `;
          updateParams = [resolvedTargetId, userId, resolvedTargetId, conversationId, tenantId];
          logger.info('✅ WhatsApp Cloud DEPARTMENT query built', {
            transferredToDepartment: resolvedTargetId,
            departmentId: resolvedTargetId,
            transferredByUserId: userId,
            conversationId,
            tenantId
          });
        }
      } else if (finalTargetType === 'user') {
        if (finalSource === 'whatsapp_web') {
          logger.info('📝 Building Evolution (whatsapp_web) USER transfer query');
          updateQuery = `
            UPDATE ${tableName}
            SET 
              assigned_user_id = ?,
              claimed_at = NOW(),
              is_claimed = TRUE,
              transferred_at = NOW(),
              transferred_by_user_id = ?,
              status = 'attended',
              updated_at = NOW()
            WHERE id = ? AND tenant_id = ?
          `;
          updateParams = [targetUserId, userId, conversationId, tenantId];
          logger.info('✅ Evolution USER query built', {
            assignedUserId: targetUserId,
            transferredByUserId: userId,
            conversationId,
            tenantId
          });
        } else {
          logger.info('📝 Building WhatsApp Cloud USER transfer query');
          updateQuery = `
            UPDATE ${tableName}
            SET 
              claimed_by_user_id = ?,
              claimed_at = NOW(),
              transferred_at = NOW(),
              transferred_by_user_id = ?,
              assigned_to_user_id = ?,
              status = 'open',
              updated_at = NOW()
            WHERE id = ? AND tenant_id = ?
          `;
          updateParams = [targetUserId, userId, targetUserId, conversationId, tenantId];
          logger.info('✅ WhatsApp Cloud USER query built', {
            claimedByUserId: targetUserId,
            assignedToUserId: targetUserId,
            transferredByUserId: userId,
            conversationId,
            tenantId
          });
        }
      }

      logger.info('🚀 Executing UPDATE query', {
        query: updateQuery.replace(/\s+/g, ' ').trim(),
        params: updateParams
      });

      // Execute update
      const [updateResult] = await connection.execute(updateQuery, updateParams);

      logger.info('✅ UPDATE query executed successfully', {
        affectedRows: updateResult.affectedRows,
        changedRows: updateResult.changedRows,
        warningCount: updateResult.warningCount
      });

      if (updateResult.affectedRows === 0) {
        logger.warn('⚠️ No rows affected by UPDATE query', {
          conversationId,
          tenantId,
          tableName
        });
      }

      // Log transfer in conversation_notes
      logger.info('📝 Logging transfer action');
      try {
        const transferNote = `Transferred to ${finalTargetType}: ${resolvedTargetName}${reason ? ` - ${reason}` : ''}`;
        
        // Use conversation_notes for both Cloud and Evolution
        logger.info('💾 Inserting transfer note into conversation_notes');
        await connection.execute(
          `INSERT INTO conversation_notes (
            tenant_id, conversation_id, contact_phone, note_text, note_type,
            created_by_user_id, created_by_name, is_internal_note, created_at
          ) VALUES (?, ?, ?, ?, 'transfer', ?, ?, TRUE, NOW())`,
          [tenantId, conversationId, conversation[phoneField], transferNote, userId, req.user.name || 'User']
        );
        logger.info('✅ Transfer note inserted successfully', {
          conversationId,
          noteText: transferNote,
          userId,
          userName: req.user.name
        });
      } catch (noteError) {
        // Continue even if note insertion fails
        logger.warn('⚠️ Could not create transfer note', {
          error: noteError.message,
          code: noteError.code,
          conversationId,
          stack: noteError.stack
        });
      }

      await connection.commit();

      logger.info('🎉 CONVERSATION TRANSFERRED SUCCESSFULLY', {
        conversationId,
        userId,
        userName: req.user.name,
        tenantId,
        finalTargetType,
        targetId: resolvedTargetId,
        targetName: resolvedTargetName,
        finalSource,
        tableName
      });

      // Emit Socket.IO events for real-time updates
      logger.info('📡 Emitting Socket.IO events');
      const io = req.app.get('io');
      if (io) {
        const tenantNamespace = io.of(`/tenant/${tenantId}`);
        
        // Emit transfer event
        tenantNamespace.emit('conversation-transferred', {
          conversationId,
          targetType: finalTargetType,
          targetId: resolvedTargetId,
          targetName: resolvedTargetName,
          transferredBy: {
            id: userId,
            name: req.user.name
          },
          source: finalSource,
          timestamp: new Date().toISOString()
        });

        // Emit specific event for WhatsApp Cloud
        if (finalSource === 'whatsapp_cloud') {
          tenantNamespace.emit('whatsapp-cloud:conversation-transferred', {
            conversationId,
            targetType: finalTargetType,
            targetId: resolvedTargetId,
            targetName: resolvedTargetName,
            transferredBy: userId,
            timestamp: new Date().toISOString()
          });
        }

        // Emit specific event for Evolution/WhatsApp Web
        if (finalSource === 'whatsapp_web') {
          tenantNamespace.emit('whatsapp-web:conversation-transferred', {
            conversationId,
            targetType: finalTargetType,
            targetId: resolvedTargetId,
            targetName: resolvedTargetName,
            transferredBy: userId,
            timestamp: new Date().toISOString()
          });
        }

        logger.info('✅ Socket.IO events emitted successfully');
      } else {
        logger.warn('⚠️ Socket.IO not available, skipping real-time notifications');
      }

      return res.json({
        success: true,
        message: 'Conversation transferred successfully',
        data: {
          conversationId,
          targetType: finalTargetType,
          targetId: resolvedTargetId,
          targetName: resolvedTargetName,
          transferredAt: new Date().toISOString(),
          source: finalSource
        }
      });
    } catch (error) {
      await connection.rollback();
      logger.error('❌ ERROR TRANSFERRING CONVERSATION', {
        error: error.message,
        stack: error.stack,
        conversationId: req.params.id,
        userId: req.user.id,
        tenantId: req.user.tenantId || req.tenantId,
        requestBody: req.body
      });
      
      return res.status(500).json({
        success: false,
        message: 'Failed to transfer conversation',
        error: process.env.NODE_ENV === 'development' ? error.message : undefined
      });
    } finally {
      connection.release();
    }
  });

  /**
   * Get transfer options (stores, departments, users)
   * GET /api/user/conversations/transfer-options
   * GET /api/user/whatsapp-cloud/conversations/transfer-options
   */
  static getTransferOptions = asyncHandler(async (req, res) => {
    const tenantId = req.user.tenantId || req.tenantId;
    const userId = req.user.id;

    try {
      // Get stores
      const [stores] = await pool.execute(
        `SELECT id, name, description, is_active 
         FROM stores 
         WHERE tenant_id = ? AND is_active = TRUE
         ORDER BY name ASC`,
        [tenantId]
      );

      // Get departments
      const [departments] = await pool.execute(
        `SELECT id, name, description, is_active 
         FROM departments 
         WHERE tenant_id = ? AND is_active = TRUE
         ORDER BY name ASC`,
        [tenantId]
      );

      // Get users (excluding current user)
      const [users] = await pool.execute(
        `SELECT u.id, u.name, u.email, u.role, u.store_id, u.department_id,
                s.name as store_name, d.name as department_name
         FROM users u
         LEFT JOIN stores s ON u.store_id = s.id
         LEFT JOIN departments d ON u.department_id = d.id
         WHERE u.tenant_id = ? AND u.active = TRUE AND u.id != ?
         ORDER BY u.name ASC`,
        [tenantId, userId]
      );

      logger.info('Transfer options retrieved', {
        tenantId,
        userId,
        storesCount: stores.length,
        departmentsCount: departments.length,
        usersCount: users.length
      });

      return res.json({
        success: true,
        data: {
          stores,
          departments,
          users
        }
      });
    } catch (error) {
      logger.error('Error getting transfer options', {
        error: error.message,
        tenantId,
        userId
      });
      
      return res.status(500).json({
        success: false,
        message: 'Failed to load transfer options'
      });
    }
  });

  /**
   * Get transfer history for a conversation
   * GET /api/user/conversations/:id/transfer-history
   * GET /api/user/whatsapp-cloud/conversations/:id/transfer-history
   */
  static getTransferHistory = asyncHandler(async (req, res) => {
    const conversationId = req.params.id;
    const tenantId = req.user.tenantId || req.tenantId;
    const source = req.query.source || 'whatsapp_cloud';

    try {
      let history = [];

      if (source === 'whatsapp_cloud') {
        // Get from conversation_notes
        const [notes] = await pool.execute(
          `SELECT cn.*, u.name as user_name
           FROM conversation_notes cn
           LEFT JOIN users u ON cn.created_by_user_id = u.id
           WHERE cn.conversation_id = ? AND cn.tenant_id = ? AND cn.note_type = 'transfer'
           ORDER BY cn.created_at DESC`,
          [conversationId, tenantId]
        );
        history = notes;
      } else {
        // Get from conversation_logs
        try {
          const [logs] = await pool.execute(
            `SELECT cl.*, u.name as user_name
             FROM conversation_logs cl
             LEFT JOIN users u ON cl.user_id = u.id
             WHERE cl.conversation_id = ? AND cl.action = 'transferred'
             ORDER BY cl.created_at DESC`,
            [conversationId]
          );
          history = logs;
        } catch (error) {
          // Table might not exist
          logger.warn('conversation_logs table not found', { error: error.message });
        }
      }

      return res.json({
        success: true,
        data: history
      });
    } catch (error) {
      logger.error('Error getting transfer history', {
        error: error.message,
        conversationId,
        tenantId
      });
      
      return res.status(500).json({
        success: false,
        message: 'Failed to load transfer history'
      });
    }
  });
}

module.exports = ConversationTransferController;
