const express = require('express');
const router = express.Router();
const TKGMigrationService = require('../services/tkg-migration-service');

/**
 * Template Knowledge Graph Migration Routes
 * Handles migration from PostgreSQL to Neo4j
 */

// POST /api/tkg-migration/migrate - Migrate all templates to TKG
router.post('/migrate', async (req, res) => {
  try {
    console.log('🚀 Starting TKG migration...');
    
    const migrationService = new TKGMigrationService();
    await migrationService.migrateAllTemplates();
    
    const stats = await migrationService.getMigrationStats();
    await migrationService.close();
    
    res.json({
      success: true,
      data: stats,
      message: 'TKG migration completed successfully'
    });
  } catch (error) {
    console.error('❌ TKG migration failed:', error.message);
    res.status(500).json({
      success: false,
      error: 'Migration failed',
      message: error.message
    });
  }
});

// POST /api/tkg-migration/cleanup-duplicates - Clean up duplicate templates in TKG
router.post('/cleanup-duplicates', async (req, res) => {
  try {
    console.log('🧹 Starting TKG duplicate cleanup...');
    
    const migrationService = new TKGMigrationService();
    const result = await migrationService.neo4j.cleanupDuplicates();
    await migrationService.close();
    
    if (result.success) {
      res.json({
        success: true,
        message: 'TKG duplicate cleanup completed successfully',
        data: {
          removedCount: result.removedCount,
          duplicateCount: result.duplicateCount,
          totalTemplates: result.totalTemplates
        }
      });
    } else {
      res.status(500).json({
        success: false,
        error: 'TKG cleanup failed',
        message: result.error
      });
    }
  } catch (error) {
    console.error('❌ TKG duplicate cleanup failed:', error.message);
    res.status(500).json({
      success: false,
      error: 'TKG cleanup failed',
      message: error.message
    });
  }
});

// GET /api/tkg-migration/stats - Get migration statistics
router.get('/stats', async (req, res) => {
  try {
    const migrationService = new TKGMigrationService();
    const stats = await migrationService.getMigrationStats();
    await migrationService.close();
    
    res.json({
      success: true,
      data: stats,
      message: 'TKG migration statistics'
    });
  } catch (error) {
    console.error('❌ Failed to get migration stats:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to get stats',
      message: error.message
    });
  }
});

// POST /api/tkg-migration/clear - Clear TKG data
router.post('/clear', async (req, res) => {
  try {
    console.log('🧹 Clearing TKG data...');
    
    const migrationService = new TKGMigrationService();
    await migrationService.neo4j.clearTKG();
    await migrationService.close();
    
    res.json({
      success: true,
      message: 'TKG data cleared successfully'
    });
  } catch (error) {
    console.error('❌ Failed to clear TKG:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to clear TKG',
      message: error.message
    });
  }
});

// POST /api/tkg-migration/template/:id - Migrate single template
router.post('/template/:id', async (req, res) => {
  try {
    const { id } = req.params;
    console.log(`🔄 Migrating template ${id} to TKG...`);
    
    const migrationService = new TKGMigrationService();
    await migrationService.migrateTemplateToTKG(id);
    await migrationService.close();
    
    res.json({
      success: true,
      message: `Template ${id} migrated to TKG successfully`
    });
  } catch (error) {
    console.error(`❌ Failed to migrate template ${req.params.id}:`, error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to migrate template',
      message: error.message
    });
  }
});

// GET /api/tkg-migration/template/:id/tech-stack - Get template tech stack from TKG
router.get('/template/:id/tech-stack', async (req, res) => {
  try {
    const { id } = req.params;
    
    const migrationService = new TKGMigrationService();
    const techStack = await migrationService.neo4j.getTemplateTechStack(id);
    await migrationService.close();
    
    res.json({
      success: true,
      data: techStack,
      message: `Tech stack for template ${id}`
    });
  } catch (error) {
    console.error(`❌ Failed to get tech stack for template ${req.params.id}:`, error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to get tech stack',
      message: error.message
    });
  }
});

// GET /api/tkg-migration/template/:id/features - Get template features from TKG
router.get('/template/:id/features', async (req, res) => {
  try {
    const { id } = req.params;
    
    const migrationService = new TKGMigrationService();
    const features = await migrationService.neo4j.getTemplateFeatures(id);
    await migrationService.close();
    
    res.json({
      success: true,
      data: features,
      message: `Features for template ${id}`
    });
  } catch (error) {
    console.error(`❌ Failed to get features for template ${req.params.id}:`, error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to get features',
      message: error.message
    });
  }
});

// GET /api/tkg-migration/health - Health check for TKG
router.get('/health', async (req, res) => {
  try {
    const migrationService = new TKGMigrationService();
    const isConnected = await migrationService.neo4j.testConnection();
    await migrationService.close();
    
    res.json({
      success: true,
      data: {
        neo4j_connected: isConnected,
        timestamp: new Date().toISOString()
      },
      message: 'TKG health check completed'
    });
  } catch (error) {
    console.error('❌ TKG health check failed:', error.message);
    res.status(500).json({
      success: false,
      error: 'Health check failed',
      message: error.message
    });
  }
});

module.exports = router;
