const express = require('express');
const router = express.Router();

/**
 * Auto TKG Migration API Routes
 * Provides endpoints for managing automated TKG migration
 */

// GET /api/auto-tkg-migration/status - Get migration status
router.get('/status', async (req, res) => {
  try {
    const autoTKGMigration = req.app.get('autoTKGMigration');
    
    if (!autoTKGMigration) {
      return res.status(503).json({
        success: false,
        error: 'Auto TKG migration service not available',
        message: 'The automated TKG migration service is not initialized'
      });
    }

    const status = await autoTKGMigration.getStatus();
    
    res.json({
      success: true,
      data: status.data,
      message: 'Auto TKG migration status retrieved successfully'
    });
  } catch (error) {
    console.error('❌ Error getting auto TKG migration status:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to get migration status',
      message: error.message
    });
  }
});

// POST /api/auto-tkg-migration/trigger - Manually trigger migration
router.post('/trigger', async (req, res) => {
  try {
    const autoTKGMigration = req.app.get('autoTKGMigration');
    
    if (!autoTKGMigration) {
      return res.status(503).json({
        success: false,
        error: 'Auto TKG migration service not available',
        message: 'The automated TKG migration service is not initialized'
      });
    }

    console.log('🔄 Manual TKG migration triggered via API...');
    const result = await autoTKGMigration.triggerMigration();
    
    if (result.success) {
      res.json({
        success: true,
        message: result.message,
        data: {
          triggered: true,
          timestamp: new Date().toISOString()
        }
      });
    } else {
      res.status(500).json({
        success: false,
        error: 'Migration failed',
        message: result.message
      });
    }
  } catch (error) {
    console.error('❌ Error triggering auto TKG migration:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to trigger migration',
      message: error.message
    });
  }
});

// POST /api/auto-tkg-migration/migrate-template/:id - Migrate specific template
router.post('/migrate-template/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const autoTKGMigration = req.app.get('autoTKGMigration');
    
    if (!autoTKGMigration) {
      return res.status(503).json({
        success: false,
        error: 'Auto TKG migration service not available',
        message: 'The automated TKG migration service is not initialized'
      });
    }

    console.log(`🔄 Manual template migration triggered for template ${id}...`);
    const result = await autoTKGMigration.migrateTemplate(id);
    
    if (result.success) {
      res.json({
        success: true,
        message: result.message,
        data: {
          templateId: id,
          migrated: true,
          timestamp: new Date().toISOString()
        }
      });
    } else {
      res.status(500).json({
        success: false,
        error: 'Template migration failed',
        message: result.message
      });
    }
  } catch (error) {
    console.error('❌ Error migrating template:', error.message);
    res.status(500).json({
      success: false,
      error: 'Failed to migrate template',
      message: error.message
    });
  }
});

// GET /api/auto-tkg-migration/health - Health check for auto migration service
router.get('/health', (req, res) => {
  const autoTKGMigration = req.app.get('autoTKGMigration');
  
  if (!autoTKGMigration) {
    return res.status(503).json({
      success: false,
      status: 'unavailable',
      message: 'Auto TKG migration service not initialized'
    });
  }

  res.json({
    success: true,
    status: 'healthy',
    message: 'Auto TKG migration service is running',
    data: {
      service: 'auto-tkg-migration',
      version: '1.0.0',
      features: {
        auto_migration: true,
        periodic_checks: true,
        manual_triggers: true,
        template_specific_migration: true
      }
    }
  });
});

module.exports = router;
