# All files / controllers EvolutionInstanceController.js

0% Statements 0/242
0% Branches 0/129
0% Functions 0/25
0% Lines 0/238

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    850
    851
    852
    853
    854
    855
    856
    857
    858
    859
    860
    861
    862
    863
    864
    865
    866
    867
    868
    869
    870
    871
    872
    873
    874
    875
    876
    877
    878
    879
    880
    881
    882
    883
    884
    885
    886
    887
    888
    889
    890
    891
    892
    893
    894
    895
    896
    897
    898
    899
    900
    901
    902

     /**
     * 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
          });
        }
      }
    }

    module.exports = EvolutionInstanceController;