const express = require('express');
const { Router } = require('express');
const MigrationService = require('../services/MigrationService');
const dbManager = require('../database/DatabaseManager');
const { requireAdminAuth } = require('../middlewares/auth');
const { requireCsrf } = require('../middlewares/csrf');

const router = Router();

router.get('/status', async (req, res) => {
    /* 
        #swagger.tags = ['System Migration']
        #swagger.summary = 'Get migration status'
        #swagger.description = 'Returns current database migration status and history'
        #swagger.responses[200] = {
            description: 'Migration status',
            schema: {
                migrationComplete: true,
                jsonBackupExists: true,
                sqliteActive: true,
                lastMigration: '2025-11-01T10:00:00Z'
            }
        }
    */
    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 
        });
    }
});

// Protect dangerous migration operations with admin auth
router.post('/migrate', requireAdminAuth, requireCsrf, async (req, res) => {
    /* 
        #swagger.tags = ['System Migration']
        #swagger.summary = 'Manually trigger migration'
        #swagger.description = 'Triggers manual migration from JSON to SQLite database'
        #swagger.responses[200] = {
            description: 'Migration successful',
            schema: {
                success: true,
                message: 'Migration completed successfully',
                groupsMigrated: 24,
                imagesMigrated: 348
            }
        }
        #swagger.responses[500] = {
            description: 'Migration failed'
        }
    */
    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 
        });
    }
});

router.post('/rollback', requireAdminAuth, requireCsrf, async (req, res) => {
    /* 
        #swagger.tags = ['System Migration']
        #swagger.summary = 'Rollback to JSON'
        #swagger.description = 'Emergency rollback from SQLite to JSON file storage'
        #swagger.responses[200] = {
            description: 'Rollback successful',
            schema: {
                success: true,
                message: 'Rolled back to JSON successfully',
                groupsRestored: 24
            }
        }
        #swagger.responses[500] = {
            description: 'Rollback failed'
        }
    */
    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 
        });
    }
});

router.get('/health', async (req, res) => {
    /* 
        #swagger.tags = ['System Migration']
        #swagger.summary = 'Database health check'
        #swagger.description = 'Checks database connectivity and health status'
        #swagger.responses[200] = {
            description: 'Database healthy',
            schema: {
                database: {
                    healthy: true,
                    status: 'OK'
                }
            }
        }
        #swagger.responses[500] = {
            description: 'Database unhealthy',
            schema: {
                database: {
                    healthy: false,
                    status: 'ERROR',
                    error: 'Connection failed'
                }
            }
        }
    */
    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;