const express = require('express');
const { Router } = require('express');
const MigrationService = require('../services/MigrationService');
const dbManager = require('../database/DatabaseManager');

const router = Router();

// Migration Status abrufen
router.get('/migration/status', async (req, res) => {
    try {
        const status = await MigrationService.getMigrationStatus();
        res.json(status);
    } catch (error) {
        console.error('Fehler beim Abrufen des Migrationsstatus:', error);
        res.status(500).json({ 
            error: 'Internal server error',
            message: 'Fehler beim Abrufen des Migrationsstatus',
            details: error.message 
        });
    }
});

// Manuelle Migration starten
router.post('/migration/migrate', async (req, res) => {
    try {
        const result = await MigrationService.migrateJsonToSqlite();
        res.json(result);
    } catch (error) {
        console.error('Fehler bei der Migration:', error);
        res.status(500).json({ 
            error: 'Migration failed',
            message: 'Fehler bei der Migration',
            details: error.message 
        });
    }
});

// Rollback zu JSON (Notfall)
router.post('/migration/rollback', async (req, res) => {
    try {
        const result = await MigrationService.rollbackToJson();
        res.json(result);
    } catch (error) {
        console.error('Fehler beim Rollback:', error);
        res.status(500).json({ 
            error: 'Rollback failed',
            message: 'Fehler beim Rollback',
            details: error.message 
        });
    }
});

// Datenbank Health Check
router.get('/migration/health', async (req, res) => {
    try {
        const isHealthy = await dbManager.healthCheck();
        res.json({ 
            database: {
                healthy: isHealthy,
                status: isHealthy ? 'OK' : 'ERROR'
            }
        });
    } catch (error) {
        console.error('Health Check fehlgeschlagen:', error);
        res.status(500).json({ 
            database: {
                healthy: false,
                status: 'ERROR',
                error: error.message
            }
        });
    }
});

module.exports = router;