const express = require('express');
const router = express.Router();
const ComprehensiveNamespaceMigrationService = require('../services/comprehensive-namespace-migration');

/**
 * POST /api/comprehensive-migration/run
 * Run comprehensive namespace migration for all templates
 */
router.post('/run', async (req, res) => {
  const migrationService = new ComprehensiveNamespaceMigrationService();
  
  try {
    console.log('🚀 Starting comprehensive namespace migration...');
    
    const result = await migrationService.runComprehensiveMigration();
    
    await migrationService.close();
    
    if (result.success) {
      res.json({
        success: true,
        data: result.stats,
        message: 'Comprehensive namespace migration completed successfully'
      });
    } else {
      res.status(500).json({
        success: false,
        error: result.error,
        stats: result.stats,
        message: 'Comprehensive namespace migration failed'
      });
    }
    
  } catch (error) {
    console.error('❌ Comprehensive migration route error:', error.message);
    
    await migrationService.close();
    
    res.status(500).json({
      success: false,
      error: 'Internal server error',
      message: error.message
    });
  }
});

/**
 * GET /api/comprehensive-migration/status
 * Get migration status for all templates
 */
router.get('/status', async (req, res) => {
  const migrationService = new ComprehensiveNamespaceMigrationService();
  
  try {
    const templates = await migrationService.getAllTemplatesWithFeatures();
    
    const statusData = [];
    
    for (const template of templates) {
      const existingData = await migrationService.checkExistingData(template.id);
      
      statusData.push({
        template_id: template.id,
        template_title: template.title,
        template_category: template.category,
        feature_count: template.features.length,
        has_permutations: existingData.hasPermutations,
        has_combinations: existingData.hasCombinations,
        status: existingData.hasPermutations && existingData.hasCombinations ? 'complete' : 'incomplete'
      });
    }
    
    await migrationService.close();
    
    const completeCount = statusData.filter(t => t.status === 'complete').length;
    const incompleteCount = statusData.filter(t => t.status === 'incomplete').length;
    
    res.json({
      success: true,
      data: {
        templates: statusData,
        summary: {
          total_templates: templates.length,
          complete: completeCount,
          incomplete: incompleteCount,
          completion_percentage: templates.length > 0 ? Math.round((completeCount / templates.length) * 100) : 0
        }
      },
      message: `Migration status: ${completeCount}/${templates.length} templates complete`
    });
    
  } catch (error) {
    console.error('❌ Migration status route error:', error.message);
    
    await migrationService.close();
    
    res.status(500).json({
      success: false,
      error: 'Internal server error',
      message: error.message
    });
  }
});

/**
 * POST /api/comprehensive-migration/process-template/:templateId
 * Process a specific template (generate permutations and combinations)
 */
router.post('/process-template/:templateId', async (req, res) => {
  const { templateId } = req.params;
  const migrationService = new ComprehensiveNamespaceMigrationService();
  
  try {
    console.log(`🔄 Processing template: ${templateId}`);
    
    // Get template with features
    const templates = await migrationService.getAllTemplatesWithFeatures();
    const template = templates.find(t => t.id === templateId);
    
    if (!template) {
      return res.status(404).json({
        success: false,
        error: 'Template not found',
        message: `Template with ID ${templateId} not found`
      });
    }
    
    // Process the template
    await migrationService.processTemplate(template);
    
    await migrationService.close();
    
    res.json({
      success: true,
      data: {
        template_id: templateId,
        template_title: template.title,
        feature_count: template.features.length
      },
      message: `Template ${template.title} processed successfully`
    });
    
  } catch (error) {
    console.error('❌ Process template route error:', error.message);
    
    await migrationService.close();
    
    res.status(500).json({
      success: false,
      error: 'Internal server error',
      message: error.message
    });
  }
});

module.exports = router;
