/**
 * Script to update all controllers to use unified response format
 * This script adds the response utility import and updates response format
 * 
 * Run: node backend/src/scripts/updateResponseFormat.js
 */

const fs = require('fs');
const path = require('path');

const controllersDir = path.join(__dirname, '../controllers');

// List of controller files to update
const controllerFiles = [
  'userController.js',
  'serviceController.js',
  'appointmentController.js',
  'notificationController.js',
  'invitationController.js',
  'withdrawalController.js',
  'uploadController.js',
  'adminAuthController.js',
  'adminUserController.js',
  'adminAppointmentController.js',
  'adminWithdrawalController.js',
  'adminServiceController.js',
  'adminStatisticsController.js',
  'adminTranslationController.js',
];

console.log('Starting response format update...\n');

controllerFiles.forEach(file => {
  const filePath = path.join(controllersDir, file);
  
  if (!fs.existsSync(filePath)) {
    console.log(`⚠️  Skipping ${file} - file not found`);
    return;
  }

  try {
    let content = fs.readFileSync(filePath, 'utf8');
    
    // Check if already updated
    if (content.includes("require('../utils/response')")) {
      console.log(`✓ ${file} - already updated`);
      return;
    }

    // Add response utility import after other requires
    const requirePattern = /(const .+ = require\(.+\);?\n)+/;
    const match = content.match(requirePattern);
    
    if (match) {
      const lastRequire = match[0];
      const insertPosition = content.indexOf(lastRequire) + lastRequire.length;
      const importStatement = "const { sendSuccess, sendError, sendPaginated } = require('../utils/response');\n";
      
      content = content.slice(0, insertPosition) + importStatement + content.slice(insertPosition);
      
      // Replace success responses
      content = content.replace(
        /res\.status\((\d+)\)\.json\(\{\s*success:\s*true,\s*data:\s*(.+?)\s*\}\);?/gs,
        (match, statusCode, data) => {
          return `sendSuccess(res, ${data.trim()});`;
        }
      );

      // Replace error responses
      content = content.replace(
        /res\.status\((\d+)\)\.json\(\{\s*success:\s*false,\s*error:\s*\{[^}]+message:\s*['"](.+?)['"]/gs,
        (match, statusCode, message) => {
          return `sendError(res, '${message}', ${statusCode}, ${statusCode}`;
        }
      );

      fs.writeFileSync(filePath, content, 'utf8');
      console.log(`✓ ${file} - updated successfully`);
    } else {
      console.log(`⚠️  ${file} - could not find require statements`);
    }
  } catch (error) {
    console.error(`✗ ${file} - error: ${error.message}`);
  }
});

console.log('\n✓ Response format update completed!');
console.log('\nNote: Please review the changes and test thoroughly.');
console.log('Some complex response structures may need manual adjustment.');
