#!/usr/bin/env node

/**
 * Cleanup Script for Old Authentication System
 * 
 * This script helps remove old authentication files after successful migration
 * to the new modular auth system.
 * 
 * Usage: node scripts/cleanup-old-auth.js [--dry-run]
 */

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

const OLD_AUTH_FILES = [
  'src/lib/auth-unified.ts',
  'src/lib/auth.ts',
  'src/lib/simple-auth.ts',
  'src/lib/super-admin-auth.ts',
  'src/lib/territory-manager-auth.ts',
  'src/components/ProtectedRoute.astro',
  'src/components/AuthLoader.astro',
  'src/pages/api/auth/login.ts',
  'src/pages/api/auth/logout.ts',
  'src/pages/api/auth/session.ts',
  'src/pages/api/admin/auth-check.ts',
];

const OLD_API_FILES = [
  'src/lib/api-client.ts',
  'src/lib/api-router.ts',
  'src/lib/admin-api-router.ts',
  'src/lib/territory-manager-api.ts',
  'src/lib/territory-manager-router.ts',
];

const DEPRECATED_FILES = [
  'src/lib/super-admin-types.ts',
  'src/lib/super-admin-utils.ts',
  'src/lib/territory-manager-types.ts',
];

function main() {
  const args = process.argv.slice(2);
  const dryRun = args.includes('--dry-run');
  
  console.log('🧹 Old Authentication System Cleanup');
  console.log('=====================================');
  
  if (dryRun) {
    console.log('🔍 DRY RUN MODE - No files will be deleted');
    console.log('');
  }
  
  // Check for new auth system
  if (!fs.existsSync('src/lib/auth/index.ts')) {
    console.error('❌ New auth system not found at src/lib/auth/index.ts');
    console.error('Please ensure the new auth system is properly installed before cleanup.');
    process.exit(1);
  }
  
  console.log('✅ New auth system found');
  console.log('');
  
  // Cleanup old auth files
  console.log('📁 Cleaning up old authentication files:');
  cleanupFiles(OLD_AUTH_FILES, dryRun);
  
  console.log('');
  console.log('📁 Cleaning up old API client files:');
  cleanupFiles(OLD_API_FILES, dryRun);
  
  console.log('');
  console.log('📁 Cleaning up deprecated files:');
  cleanupFiles(DEPRECATED_FILES, dryRun);
  
  console.log('');
  console.log('🔍 Checking for remaining references...');
  checkForReferences();
  
  console.log('');
  if (dryRun) {
    console.log('🔍 Dry run completed. Run without --dry-run to perform cleanup.');
  } else {
    console.log('✅ Cleanup completed successfully!');
    console.log('');
    console.log('Next steps:');
    console.log('1. Run your tests to ensure everything works');
    console.log('2. Update any remaining import statements');
    console.log('3. Review and update documentation');
    console.log('4. Deploy to staging for testing');
  }
}

function cleanupFiles(files, dryRun) {
  let deletedCount = 0;
  let skippedCount = 0;
  
  for (const file of files) {
    if (fs.existsSync(file)) {
      if (dryRun) {
        console.log(`  🗑️  Would delete: ${file}`);
      } else {
        try {
          fs.unlinkSync(file);
          console.log(`  ✅ Deleted: ${file}`);
          deletedCount++;
        } catch (error) {
          console.error(`  ❌ Failed to delete ${file}: ${error.message}`);
        }
      }
    } else {
      console.log(`  ⏭️  Not found: ${file}`);
      skippedCount++;
    }
  }
  
  if (!dryRun) {
    console.log(`  📊 Deleted: ${deletedCount}, Skipped: ${skippedCount}`);
  }
}

function checkForReferences() {
  const filesToCheck = [
    'src/pages/login.astro',
    'src/pages/dashboard.astro',
    'src/layouts/SecureLayout.astro',
    'src/components/Navigation.astro',
  ];
  
  const oldImports = [
    'auth-unified',
    'simple-auth',
    'super-admin-auth',
    'territory-manager-auth',
    'api-client',
    'api-router',
    'admin-api-router',
    'ProtectedRoute',
    'AuthLoader',
  ];
  
  let foundReferences = false;
  
  for (const file of filesToCheck) {
    if (fs.existsSync(file)) {
      const content = fs.readFileSync(file, 'utf8');
      
      for (const importName of oldImports) {
        if (content.includes(importName)) {
          console.log(`  ⚠️  Found reference to '${importName}' in ${file}`);
          foundReferences = true;
        }
      }
    }
  }
  
  if (!foundReferences) {
    console.log('  ✅ No old auth references found in key files');
  } else {
    console.log('  ⚠️  Please update the files above to use the new auth system');
  }
}

// Backup function
function createBackup() {
  const backupDir = `backups/auth-backup-${Date.now()}`;
  fs.mkdirSync(backupDir, { recursive: true });
  
  const allFiles = [...OLD_AUTH_FILES, ...OLD_API_FILES, ...DEPRECATED_FILES];
  
  for (const file of allFiles) {
    if (fs.existsSync(file)) {
      const backupPath = path.join(backupDir, file);
      const backupDirPath = path.dirname(backupPath);
      
      fs.mkdirSync(backupDirPath, { recursive: true });
      fs.copyFileSync(file, backupPath);
      console.log(`  💾 Backed up: ${file} -> ${backupPath}`);
    }
  }
  
  console.log(`✅ Backup created in ${backupDir}`);
}

if (require.main === module) {
  main();
}