/**
 * EvolutionInstanceController.js
 * 
 * Controller for Evolution API instance management
 * Handles instance creation, connection, and management
 * 
 * @module controllers/EvolutionInstanceController
 */

const { logger } = require('../config/logger');
const EvolutionInstance = require('../models/EvolutionInstance');
const EvolutionAPIService = require('../services/EvolutionAPIService');

/**
 * Get Evolution API configuration from superadmin settings
 */
async function getEvolutionConfig() {
  const pool = require('../config/database').pool;
  const [settings] = await pool.execute(
    `SELECT setting_key, setting_value FROM system_settings_kv 
     WHERE setting_key IN ('evolution_enabled', 'evolution_api_url', 'evolution_api_key', 'evolution_webhook_base_url')`
  );

  const config = {};
  settings.forEach(row => {
    config[row.setting_key] = row.setting_value;
  });

  logger.info('Evolution config retrieved from database', {
    hasSettings: settings.length > 0,
    settingsCount: settings.length,
    keys: Object.keys(config),
    evolution_enabled: config.evolution_enabled,
    evolution_api_url: config.evolution_api_url,
    hasApiKey: !!config.evolution_api_key
  });

  return config;
}

/**
 * Execute Evolution API call with superadmin configuration
 */
async function withEvolutionConfig(callback) {
  const config = await getEvolutionConfig();
  
  logger.info('Evolution config loaded', {
    enabled: config.evolution_enabled,
    hasApiUrl: !!config.evolution_api_url,
    hasApiKey: !!config.evolution_api_key
  });
  
  // Check if Evolution API is enabled
  if (config.evolution_enabled !== '1') {
    throw new Error('Evolution API is not enabled');
  }

  // Validate configuration
  if (!config.evolution_api_url || !config.evolution_api_key) {
    throw new Error('Evolution API is not properly configured');
  }

  // Temporarily override environment variables
  const originalApiUrl = process.env.EVOLUTION_API_URL;
  const originalApiKey = process.env.EVOLUTION_API_KEY;
  
  process.env.EVOLUTION_API_URL = config.evolution_api_url;
  process.env.EVOLUTION_API_KEY = config.evolution_api_key;

  try {
    return await callback(config);
  } catch (error) {
    logger.error('Error in withEvolutionConfig callback', {
      error: error.message,
      stack: error.stack
    });
    throw error;
  } finally {
    // Restore original environment variables
    if (originalApiUrl) process.env.EVOLUTION_API_URL = originalApiUrl;
    if (originalApiKey) process.env.EVOLUTION_API_KEY = originalApiKey;
  }
}

/**
 * Evolution Instance Controller
 * All methods are tenant-scoped via req.tenant.id
 */
class EvolutionInstanceController {
  /**
   * List all instances for tenant
   * GET /api/tenant/whatsapp/instances
   */
  static async listInstances(req, res) {
    try {
      const tenantId = req.tenant.id;

      logger.info(`Listing instances for tenant ${tenantId}`);

      const instances = await EvolutionInstance.getByTenantId(tenantId);
      const limitCheck = await EvolutionInstance.checkLimit(tenantId);

      res.json({
        success: true,
        data: {
          instances,
          limit: limitCheck
        }
      });
    } catch (error) {
      logger.error(`Error listing instances: ${error.message}`, { 
        tenantId: req.tenant.id,
        error: error.stack 
      });
      res.status(500).json({
        success: false,
        message: 'Failed to list instances',
        error: error.message
      });
    }
  }

  /**
   * List connected instances for conversations dropdown
   * GET /api/tenant/whatsapp/connected-instances
   */
  static async listConnectedInstances(req, res) {
    try {
      const tenantId = req.tenant.id;

      logger.info(`Listing connected instances for tenant ${tenantId}`);

      const instances = await EvolutionInstance.getByTenantId(tenantId);
      
      // Filter only connected instances
      const connectedInstances = instances
        .filter(instance => instance.status === 'connected')
        .map(instance => ({
          id: `evolution_${instance.id}`,
          type: 'evolution',
          instance_id: instance.id,
          name: instance.instance_name,
          phone_number: instance.phone_number,
          status: instance.status,
          last_connected_at: instance.last_connected_at
        }));

      res.json({
        success: true,
        data: connectedInstances
      });
    } catch (error) {
      logger.error(`Error listing connected instances: ${error.message}`, { 
        tenantId: req.tenant.id,
        error: error.stack 
      });
      res.status(500).json({
        success: false,
        message: 'Failed to list connected instances',
        error: error.message
      });
    }
  }

  /**
   * Create new instance
   * POST /api/tenant/whatsapp/instances
   * Body: { instance_name, instance_type, phone_number?, preferences? }
   */
  static async createInstance(req, res) {
    try {
      const tenantId = req.tenant.id;
      const { instance_name, instance_type, phone_number, preferences } = req.body;

      // Validate input
      if (!instance_name) {
        return res.status(400).json({
          success: false,
          message: 'Instance name is required'
        });
      }

      // Check instance limit
      const limitCheck = await EvolutionInstance.checkLimit(tenantId);
      if (!limitCheck.canCreate) {
        return res.status(403).json({
          success: false,
          message: `Instance limit reached. Your plan allows ${limitCheck.max} instance(s).`
        });
      }

      logger.info(`Creating instance for tenant ${tenantId}`, { instance_name, instance_type });

      // Generate unique instance name for Evolution API
      const evolutionInstanceName = `tenant_${tenantId}_${instance_name.toLowerCase().replace(/[^a-z0-9]/g, '_')}_${Date.now()}`;

      // Create instance using Evolution API configuration from superadmin
      const instance = await withEvolutionConfig(async (config) => {
        // Create webhook URL using configured base URL
        const webhookBaseUrl = config.evolution_webhook_base_url || process.env.EVOLUTION_WEBHOOK_BASE_URL || 'http://localhost:3000';
        const webhookUrl = `${webhookBaseUrl}/api/webhooks/evolution/${tenantId}`;

        logger.info('Creating Evolution instance with config', {
          evolutionInstanceName,
          webhookUrl,
          apiUrl: config.evolution_api_url,
          hasApiKey: !!config.evolution_api_key
        });

        // Create instance in Evolution API
        const evolutionData = await EvolutionAPIService.createInstance(
          evolutionInstanceName,
          webhookUrl,
          ['QRCODE_UPDATED', 'CONNECTION_UPDATE', 'MESSAGES_UPSERT', 'MESSAGES_UPDATE', 'SEND_MESSAGE']
        );

        logger.info('Evolution API instance created', { evolutionData });

        // Apply settings if provided
        if (preferences) {
          try {
            logger.info('Applying instance settings', { evolutionInstanceName, preferences });
            await EvolutionAPIService.setInstanceSettings(evolutionInstanceName, preferences);
            logger.info('Instance settings applied successfully', { evolutionInstanceName });
          } catch (settingsError) {
            logger.error('Failed to apply instance settings', {
              evolutionInstanceName,
              error: settingsError.message,
              preferences
            });
            // Don't fail the instance creation if settings fail
          }
        }

        // Save instance to database
        return await EvolutionInstance.create(tenantId, {
          instance_name,
          instance_type: instance_type || 'whatsapp_web',
          phone_number,
          status: 'disconnected',
          evolution_instance_id: evolutionInstanceName,
          webhook_url: webhookUrl,
          webhook_events: ['QRCODE_UPDATED', 'CONNECTION_UPDATE', 'MESSAGES_UPSERT', 'MESSAGES_UPDATE', 'SEND_MESSAGE'],
          connection_data: preferences || {}
        });
      });

      logger.info(`Instance created successfully for tenant ${tenantId}`, { 
        instanceId: instance.id,
        evolutionInstanceId: evolutionInstanceName 
      });

      res.json({
        success: true,
        message: 'Instance created successfully',
        data: instance
      });
    } catch (error) {
      logger.error(`Error creating instance: ${error.message}`, { 
        tenantId: req.tenant.id,
        error: error.stack 
      });
      
      // Check for specific error messages
      if (error.message.includes('not enabled') || error.message.includes('not properly configured')) {
        return res.status(503).json({
          success: false,
          message: error.message + '. Please contact your administrator.'
        });
      }
      
      res.status(500).json({
        success: false,
        message: 'Failed to create instance',
        error: error.message
      });
    }
  }

  /**
   * Get instance status
   * GET /api/tenant/whatsapp/instances/:id/status
   */
  static async getInstanceStatus(req, res) {
    try {
      const tenantId = req.tenant.id;
      const instanceId = req.params.id;

      let instance = await EvolutionInstance.getById(instanceId);

      if (!instance || instance.tenant_id !== tenantId) {
        return res.status(404).json({
          success: false,
          message: 'Instance not found'
        });
      }

      logger.info('Getting instance status', { 
        instanceId, 
        currentStatus: instance.status,
        evolutionInstanceId: instance.evolution_instance_id 
      });

      // Get status from Evolution API using superadmin configuration
      try {
        const evolutionStatus = await withEvolutionConfig(async () => {
          return await EvolutionAPIService.getInstanceStatus(instance.evolution_instance_id);
        });
        
        logger.info('Evolution API status received', { 
          instanceId, 
          evolutionState: evolutionStatus.state || evolutionStatus.instance?.state,
          currentLocalStatus: instance.status,
          fullEvolutionStatus: evolutionStatus
        });
        
        // Update local status if different
        // Evolution API can return state in different formats
        const state = evolutionStatus.state || evolutionStatus.instance?.state;
        
        if (state) {
          const statusMap = {
            'open': 'connected',
            'connecting': 'connecting',
            'close': 'disconnected'
          };
          
          const newStatus = statusMap[state] || 'disconnected';
          
          if (newStatus !== instance.status) {
            logger.info('Updating instance status', { 
              instanceId, 
              oldStatus: instance.status, 
              newStatus,
              evolutionState: state
            });
            
            const updateData = { status: newStatus };
            
            // If connected, update additional fields
            if (newStatus === 'connected') {
              updateData.last_connected_at = new Date().toISOString().slice(0, 19).replace('T', ' ');
              updateData.error_message = null;
              updateData.qr_code = null;
            }
            
            await EvolutionInstance.update(instanceId, updateData);
            
            // Get updated instance
            instance = await EvolutionInstance.getById(instanceId);
            
            logger.info('Instance status updated successfully', { 
              instanceId, 
              newStatus: instance.status 
            });
          }
        }

        res.json({
          success: true,
          data: {
            ...instance,
            evolution_status: evolutionStatus
          }
        });
      } catch (apiError) {
        // If Evolution API fails, return local status
        logger.error(`Evolution API status check failed`, { 
          instanceId,
          evolutionInstanceId: instance.evolution_instance_id,
          errorMessage: apiError.message,
          errorStack: apiError.stack,
          errorResponse: apiError.response?.data,
          errorStatus: apiError.response?.status
        });
        
        res.json({
          success: true,
          data: instance
        });
      }
    } catch (error) {
      logger.error(`Error getting instance status: ${error.message}`, { 
        tenantId: req.tenant.id,
        error: error.stack 
      });
      res.status(500).json({
        success: false,
        message: 'Failed to get instance status',
        error: error.message
      });
    }
  }

  /**
   * Connect instance (generate QR code)
   * POST /api/tenant/whatsapp/instances/:id/connect
   */
  static async connectInstance(req, res) {
    try {
      const tenantId = req.tenant.id;
      const instanceId = req.params.id;

      const instance = await EvolutionInstance.getById(instanceId);

      if (!instance || instance.tenant_id !== tenantId) {
        return res.status(404).json({
          success: false,
          message: 'Instance not found'
        });
      }

      logger.info(`Connecting instance ${instanceId} for tenant ${tenantId}`);

      // Connect via Evolution API using superadmin configuration
      const result = await withEvolutionConfig(async () => {
        // Connect via Evolution API - this should return QR code directly
        const connectionData = await EvolutionAPIService.connectInstance(instance.evolution_instance_id);

        logger.info('Connection data received:', { 
          instanceId,
          hasConnectionData: !!connectionData,
          connectionDataKeys: connectionData ? Object.keys(connectionData) : [],
          connectionDataSample: connectionData ? JSON.stringify(connectionData).substring(0, 500) : null
        });

        // Update instance status
        await EvolutionInstance.updateStatus(instanceId, 'connecting');

        // Try to extract QR code from connection response
        let qrCode = connectionData?.qrcode?.base64 || 
                     connectionData?.qrcode?.code || 
                     connectionData?.qrcode || 
                     connectionData?.base64 || 
                     connectionData?.code || 
                     null;

        if (qrCode) {
          logger.info('QR code found in connection response', { instanceId, qrCodeLength: qrCode.length });
          await EvolutionInstance.update(instanceId, { 
            qr_code: qrCode,
            status: 'qr_code'
          });
          
          return {
            status: 'qr_code',
            qr_code: qrCode,
            message: 'QR code generated successfully'
          };
        }

        // If no QR code in connection response, try to fetch it separately
        logger.info('No QR code in connection response, will try to fetch separately...', { instanceId });
        await new Promise(resolve => setTimeout(resolve, 3000));

        // Try to get QR code multiple times
        let attempts = 0;
        const maxAttempts = 5;

        while (!qrCode && attempts < maxAttempts) {
          attempts++;
          try {
            logger.info(`Attempt ${attempts}/${maxAttempts} to get QR code`, { instanceId });
            
            const qrData = await EvolutionAPIService.getQRCode(instance.evolution_instance_id);
            logger.info('QR code data received:', { 
              instanceId,
              attempt: attempts,
              hasData: !!qrData,
              dataKeys: qrData ? Object.keys(qrData) : [],
              fullData: qrData
            });
            
            qrCode = qrData?.qrcode?.base64 || 
                     qrData?.qrcode?.code || 
                     qrData?.qrcode || 
                     qrData?.base64 || 
                     qrData?.code || 
                     qrData?.qr || 
                     null;
            
            if (qrCode) {
              await EvolutionInstance.update(instanceId, { 
                qr_code: qrCode,
                status: 'qr_code'
              });
              logger.info('QR code saved to database', { instanceId, attempt: attempts });
              break;
            }
          } catch (qrError) {
            logger.warn(`Attempt ${attempts} failed to get QR code`, { 
              instanceId, 
              error: qrError.message,
              status: qrError.response?.status
            });
          }

          // Wait before next attempt
          if (!qrCode && attempts < maxAttempts) {
            await new Promise(resolve => setTimeout(resolve, 2000));
          }
        }

        if (!qrCode) {
          logger.warn('Could not get QR code after all attempts', { instanceId, attempts });
        }

        return {
          status: qrCode ? 'qr_code' : 'connecting',
          qr_code: qrCode,
          message: qrCode 
            ? 'QR code generated successfully' 
            : 'Connection initiated. QR code will be available shortly via polling.'
        };
      });

      res.json({
        success: true,
        message: result.message || 'Connection initiated',
        data: result
      });
    } catch (error) {
      logger.error(`Error connecting instance: ${error.message}`, { 
        tenantId: req.tenant.id,
        error: error.stack 
      });
      
      if (error.message.includes('not enabled') || error.message.includes('not properly configured')) {
        return res.status(503).json({
          success: false,
          message: error.message + '. Please contact your administrator.'
        });
      }
      
      res.status(500).json({
        success: false,
        message: 'Failed to connect instance',
        error: error.message
      });
    }
  }

  /**
   * Disconnect instance
   * POST /api/tenant/whatsapp/instances/:id/disconnect
   */
  static async disconnectInstance(req, res) {
    try {
      const tenantId = req.tenant.id;
      const instanceId = req.params.id;

      const instance = await EvolutionInstance.getById(instanceId);

      if (!instance || instance.tenant_id !== tenantId) {
        return res.status(404).json({
          success: false,
          message: 'Instance not found'
        });
      }

      logger.info(`Disconnecting instance ${instanceId} for tenant ${tenantId}`);

      // Disconnect via Evolution API using superadmin configuration
      await withEvolutionConfig(async () => {
        await EvolutionAPIService.disconnectInstance(instance.evolution_instance_id);
      });

      // Update instance status
      await EvolutionInstance.updateStatus(instanceId, 'disconnected', {
        qr_code: null,
        phone_number: null
      });

      res.json({
        success: true,
        message: 'Instance disconnected successfully'
      });
    } catch (error) {
      logger.error(`Error disconnecting instance: ${error.message}`, { 
        tenantId: req.tenant.id,
        error: error.stack 
      });
      res.status(500).json({
        success: false,
        message: 'Failed to disconnect instance',
        error: error.message
      });
    }
  }

  /**
   * Delete instance
   * DELETE /api/tenant/whatsapp/instances/:id
   */
  static async deleteInstance(req, res) {
    try {
      const tenantId = req.tenant.id;
      const instanceId = req.params.id;

      const instance = await EvolutionInstance.getById(instanceId);

      if (!instance || instance.tenant_id !== tenantId) {
        return res.status(404).json({
          success: false,
          message: 'Instance not found'
        });
      }

      logger.info(`Deleting instance ${instanceId} for tenant ${tenantId}`, {
        evolutionInstanceId: instance.evolution_instance_id
      });

      // Delete from Evolution API using superadmin configuration
      let evolutionDeleted = false;
      try {
        await withEvolutionConfig(async () => {
          logger.info('Calling Evolution API to delete instance', {
            evolutionInstanceId: instance.evolution_instance_id
          });
          
          await EvolutionAPIService.deleteInstance(instance.evolution_instance_id);
          
          logger.info('Evolution API delete successful', {
            evolutionInstanceId: instance.evolution_instance_id
          });
          
          evolutionDeleted = true;
        });
      } catch (apiError) {
        logger.error(`Evolution API delete failed`, { 
          instanceId,
          evolutionInstanceId: instance.evolution_instance_id,
          error: apiError.message,
          stack: apiError.stack
        });
        
        // Don't fail the whole operation if Evolution API delete fails
        // The instance might already be deleted or Evolution API might be down
      }

      // Soft delete from database
      await EvolutionInstance.delete(instanceId);

      logger.info('Instance deleted from database', { 
        instanceId,
        evolutionDeleted 
      });

      res.json({
        success: true,
        message: evolutionDeleted 
          ? 'Instance deleted successfully from both database and Evolution API'
          : 'Instance deleted from database (Evolution API delete failed or instance not found)',
        evolutionDeleted
      });
    } catch (error) {
      logger.error(`Error deleting instance: ${error.message}`, { 
        tenantId: req.tenant.id,
        error: error.stack 
      });
      res.status(500).json({
        success: false,
        message: 'Failed to delete instance',
        error: error.message
      });
    }
  }

  /**
   * Get QR code for instance
   * GET /api/tenant/whatsapp/instances/:id/qr
   */
  static async getQRCode(req, res) {
    try {
      const tenantId = req.tenant.id;
      const instanceId = req.params.id;

      const instance = await EvolutionInstance.getById(instanceId);

      if (!instance || instance.tenant_id !== tenantId) {
        return res.status(404).json({
          success: false,
          message: 'Instance not found'
        });
      }

      logger.info(`Getting QR code for instance ${instanceId}`, {
        evolutionInstanceId: instance.evolution_instance_id,
        currentStatus: instance.status
      });

      // If instance is already connected, no QR code needed
      if (instance.status === 'connected') {
        return res.json({
          success: false,
          message: 'Instance is already connected'
        });
      }

      // Try to get QR code from Evolution API using superadmin configuration
      try {
        logger.info('Calling withEvolutionConfig for QR code', { instanceId });
        
        const qrCode = await withEvolutionConfig(async () => {
          logger.info('Inside withEvolutionConfig callback, calling getQRCode', { 
            evolutionInstanceId: instance.evolution_instance_id 
          });
          
          try {
            const qrData = await EvolutionAPIService.getQRCode(instance.evolution_instance_id);
            
            logger.info('QR code data received from Evolution API:', { 
              instanceId,
              hasQrData: !!qrData,
              qrDataType: typeof qrData,
              qrDataKeys: qrData && typeof qrData === 'object' ? Object.keys(qrData) : [],
              fullQrData: qrData
            });
            
            const extractedQr = qrData?.qrcode?.base64 || 
                               qrData?.qrcode?.code || 
                               qrData?.qrcode || 
                               qrData?.base64 || 
                               qrData?.code || 
                               qrData?.qr || 
                               null;
            
            logger.info('Extracted QR code:', { 
              instanceId,
              hasExtractedQr: !!extractedQr,
              extractedQrLength: extractedQr ? extractedQr.length : 0
            });
            
            return extractedQr;
          } catch (apiError) {
            // If Evolution API returns 404 or error, it means QR code is not ready yet
            logger.warn('Evolution API QR code not ready', {
              instanceId,
              error: apiError.message,
              status: apiError.response?.status,
              responseData: apiError.response?.data
            });
            return null;
          }
        });

        if (qrCode) {
          logger.info('QR code found, updating database', { instanceId, qrCodeLength: qrCode.length });
          // Update in database
          await EvolutionInstance.update(instanceId, { 
            qr_code: qrCode,
            status: 'qr_code'
          });

          return res.json({
            success: true,
            data: { qr_code: qrCode }
          });
        }
      } catch (apiError) {
        logger.warn(`Error in getQRCode flow, will check cache`, { 
          instanceId, 
          errorMessage: apiError.message
        });
      }

      // Return cached QR code if available
      if (instance.qr_code) {
        logger.info('Returning cached QR code', { instanceId });
        return res.json({
          success: true,
          data: { qr_code: instance.qr_code }
        });
      }

      // No QR code available yet
      logger.info('No QR code available yet, instance may still be connecting', { 
        instanceId, 
        status: instance.status 
      });
      
      res.json({
        success: false,
        message: 'QR code not ready yet. Please wait a moment and try again.',
        status: instance.status
      });
    } catch (error) {
      logger.error(`Error getting QR code: ${error.message}`, { 
        tenantId: req.tenant.id,
        error: error.stack 
      });
      res.status(500).json({
        success: false,
        message: 'Failed to get QR code',
        error: error.message
      });
    }
  }

  /**
   * Get instance settings
   * GET /api/tenant/whatsapp/instances/:id/settings
   */
  static async getInstanceSettings(req, res) {
    try {
      const tenantId = req.tenant.id;
      const instanceId = req.params.id;

      const instance = await EvolutionInstance.getById(instanceId);

      if (!instance || instance.tenant_id !== tenantId) {
        return res.status(404).json({
          success: false,
          message: 'Instance not found'
        });
      }

      logger.info('Getting instance settings', { 
        instanceId, 
        evolutionInstanceId: instance.evolution_instance_id 
      });

      // Get settings from Evolution API
      const settings = await withEvolutionConfig(async () => {
        return await EvolutionAPIService.getInstanceSettings(instance.evolution_instance_id);
      });

      res.json({
        success: true,
        data: settings
      });
    } catch (error) {
      logger.error(`Error getting instance settings: ${error.message}`, { 
        tenantId: req.tenant.id,
        error: error.stack 
      });
      res.status(500).json({
        success: false,
        message: 'Failed to get instance settings',
        error: error.message
      });
    }
  }

  /**
   * Update instance settings
   * PUT /api/tenant/whatsapp/instances/:id/settings
   * Body: { rejectCall, alwaysOnline, readMessages, readStatus, syncFullHistory, groupsIgnore }
   */
  static async updateInstanceSettings(req, res) {
    try {
      const tenantId = req.tenant.id;
      const instanceId = req.params.id;
      const settings = req.body;

      const instance = await EvolutionInstance.getById(instanceId);

      if (!instance || instance.tenant_id !== tenantId) {
        return res.status(404).json({
          success: false,
          message: 'Instance not found'
        });
      }

      logger.info('Updating instance settings', { 
        instanceId, 
        evolutionInstanceId: instance.evolution_instance_id,
        settings 
      });

      // Update settings in Evolution API
      const updatedSettings = await withEvolutionConfig(async () => {
        return await EvolutionAPIService.setInstanceSettings(instance.evolution_instance_id, settings);
      });

      // Update connection_data in database
      await EvolutionInstance.update(instanceId, {
        connection_data: settings
      });

      res.json({
        success: true,
        message: 'Settings updated successfully',
        data: updatedSettings
      });
    } catch (error) {
      logger.error(`Error updating instance settings: ${error.message}`, { 
        tenantId: req.tenant.id,
        error: error.stack 
      });
      res.status(500).json({
        success: false,
        message: 'Failed to update instance settings',
        error: error.message
      });
    }
  }

  /**
   * Sync profile pictures for all conversations
   * POST /api/tenant/whatsapp/sync-profile-pictures
   */
  static async syncProfilePictures(req, res) {
    try {
      const tenantId = req.user.tenantId;
      logger.info('Starting profile picture sync', { tenantId });
      
      const { pool } = require('../config/database');
      const EvolutionAPIService = require('../services/EvolutionAPIService');
      
      // Get active Evolution instance for this tenant
      let instances;
      try {
        instances = await EvolutionInstance.getByTenantId(tenantId);
        logger.info('Found instances', { tenantId, count: instances ? instances.length : 0 });
      } catch (instanceError) {
        logger.error('Error finding instances', { tenantId, error: instanceError.message, stack: instanceError.stack });
        throw instanceError;
      }
      
      const activeInstance = instances.find(i => i.status === 'connected' && i.evolution_instance_id);
      
      if (!activeInstance) {
        logger.warn('No active instance found', { tenantId, instances: instances.map(i => ({ id: i.id, status: i.status, hasEvolutionId: !!i.evolution_instance_id })) });
        return res.status(400).json({
          success: false,
          message: 'No active Evolution instance found. Please connect an instance first.'
        });
      }
      
      logger.info('Active instance found', { instanceId: activeInstance.id, evolutionInstanceId: activeInstance.evolution_instance_id });
      
      // Get all conversations without profile pictures
      const [conversations] = await pool.query(
        `SELECT id, phone_number, contact_name 
         FROM conversations 
         WHERE tenant_id = ? 
         AND (profile_picture_url IS NULL OR profile_picture_url = '')
         AND phone_number IS NOT NULL
         LIMIT 50`,
        [tenantId]
      );
      
      logger.info('Found conversations to sync', { 
        tenantId, 
        count: conversations.length 
      });
      
      // Start async sync process
      const syncPromises = conversations.map(async (conv) => {
        try {
          const profilePicUrl = await EvolutionAPIService.fetchProfilePicture(
            activeInstance.evolution_instance_id,
            conv.phone_number
          );
          
          if (profilePicUrl) {
            await pool.query(
              'UPDATE conversations SET profile_picture_url = ? WHERE id = ?',
              [profilePicUrl, conv.id]
            );
            
            logger.info('Profile picture synced', { 
              conversationId: conv.id, 
              phoneNumber: conv.phone_number 
            });
            
            return { id: conv.id, success: true };
          }
          
          return { id: conv.id, success: false, reason: 'No profile picture found' };
        } catch (error) {
          logger.warn('Failed to sync profile picture', { 
            conversationId: conv.id, 
            error: error.message 
          });
          return { id: conv.id, success: false, reason: error.message };
        }
      });
      
      // Don't wait for all to complete - return immediately
      res.json({
        success: true,
        message: `Started syncing profile pictures for ${conversations.length} conversation(s)`,
        data: {
          total: conversations.length,
          instanceName: activeInstance.instance_name
        }
      });
      
      // Continue syncing in background
      Promise.all(syncPromises).then(results => {
        const successful = results.filter(r => r.success).length;
        logger.info('Profile picture sync completed', { 
          tenantId, 
          total: results.length, 
          successful 
        });
        
        // Emit socket event to refresh UI
        const io = global.io;
        if (io) {
          const tenantNamespace = io.of(`/tenant/${tenantId}`);
          tenantNamespace.emit('profile-pictures-synced', {
            total: results.length,
            successful
          });
        }
      });
      
    } catch (error) {
      logger.error('Error syncing profile pictures', { 
        tenantId: req.user?.tenantId, 
        error: error.message,
        stack: error.stack
      });
      
      res.status(500).json({
        success: false,
        message: 'Failed to sync profile pictures',
        error: error.message
      });
    }
  }
}

module.exports = EvolutionInstanceController;

