/**
 * Script to safely remove old files that have been migrated
 * Run with: node scripts/remove-old-files.js
 * 
 * This will backup and remove the files that are known to be safe to remove
 * because they've been migrated to the new structure.
 */

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

// Files that are safe to remove because they've been completely migrated
const FILES_TO_REMOVE = [
  // Client API files
  'lib/client-utils.ts',
  'lib/client-service.ts', 
  'lib/data-service.ts',
  
  // Service files
  'lib/productData.ts',
  'lib/shippingHelper.ts',
  'lib/stats-service.ts',
  'lib/server-service.ts',
  
  // API utility files
  'lib/api-utils.ts'
];

// Create backup directory
const BACKUP_DIR = path.join(__dirname, '../lib/deprecated-backup');
if (!fs.existsSync(BACKUP_DIR)) {
  fs.mkdirSync(BACKUP_DIR, { recursive: true });
  console.log(`Created backup directory: ${BACKUP_DIR}`);
}

// Process a file - back it up and remove it
function processFile(filePath) {
  const fullPath = path.join(__dirname, '..', filePath);
  
  if (!fs.existsSync(fullPath)) {
    console.log(`⚠️  ${filePath} doesn't exist, skipping`);
    return;
  }
  
  try {
    // 1. Create backup
    const backupPath = path.join(BACKUP_DIR, path.basename(filePath));
    fs.copyFileSync(fullPath, backupPath);
    console.log(`✅ Backed up ${filePath} to ${path.relative(path.join(__dirname, '..'), backupPath)}`);
    
    // 2. Remove the original file
    fs.unlinkSync(fullPath);
    console.log(`🗑️  Removed ${filePath}`);
    
    return true;
  } catch (error) {
    console.error(`❌ Error processing ${filePath}:`, error.message);
    return false;
  }
}

// Process all files
function removeFiles() {
  console.log('Starting cleanup of migrated files...\n');
  
  let successCount = 0;
  let errorCount = 0;
  
  FILES_TO_REMOVE.forEach(filePath => {
    const result = processFile(filePath);
    if (result) {
      successCount++;
    } else {
      errorCount++;
    }
  });
  
  console.log(`\nCleanup complete. Processed ${successCount + errorCount} files:`);
  console.log(`✅ ${successCount} files successfully backed up and removed`);
  
  if (errorCount > 0) {
    console.log(`❌ ${errorCount} files had errors (see above)`);
  }
  
  console.log(`\nBackups are located in: ${path.relative(path.join(__dirname, '..'), BACKUP_DIR)}`);
  console.log('You can delete this directory when you are confident the migration is complete.');
}

// Add confirmation prompt
console.log(`
⚠️  WARNING: This script will remove ${FILES_TO_REMOVE.length} files from your codebase ⚠️
 
All files will be backed up to ${path.relative(path.join(__dirname, '..'), BACKUP_DIR)} before removal.

Files to remove:
${FILES_TO_REMOVE.map(f => `- ${f}`).join('\n')}

To proceed, edit this script and uncomment the removeFiles() call at the bottom.
`);

// Uncomment this line to actually remove the files
// removeFiles(); 