const express = require('express');
const router = express.Router();
const DeletionLogRepository = require('../repositories/DeletionLogRepository');
const GroupCleanupService = require('../services/GroupCleanupService');

// GroupCleanupService ist bereits eine Instanz, keine Klasse
const cleanupService = GroupCleanupService;

// Hole Deletion Log (mit Limit)
router.get('/deletion-log', async (req, res) => {
    try {
        const limit = parseInt(req.query.limit) || 10;
        
        if (limit < 1 || limit > 1000) {
            return res.status(400).json({
                error: 'Invalid limit',
                message: 'Limit must be between 1 and 1000'
            });
        }

        const deletions = await DeletionLogRepository.getRecentDeletions(limit);
        const total = deletions.length;

        res.json({
            success: true,
            deletions: deletions,
            total: total,
            limit: limit
        });
    } catch (error) {
        console.error('Error fetching deletion log:', error);
        res.status(500).json({
            error: 'Internal server error',
            message: error.message
        });
    }
});

// Hole alle Deletion Logs
router.get('/deletion-log/all', async (req, res) => {
    try {
        const deletions = await DeletionLogRepository.getAllDeletions();

        res.json({
            success: true,
            deletions: deletions,
            total: deletions.length
        });
    } catch (error) {
        console.error('Error fetching all deletion logs:', error);
        res.status(500).json({
            error: 'Internal server error',
            message: error.message
        });
    }
});

// Hole Deletion Statistiken
router.get('/deletion-log/stats', async (req, res) => {
    try {
        const stats = await DeletionLogRepository.getDeletionStatistics();

        // Format file size
        const formatBytes = (bytes) => {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        };

        res.json({
            success: true,
            totalDeleted: stats.totalDeleted,
            totalImages: stats.totalImages,
            totalSize: formatBytes(stats.totalSize),
            totalSizeBytes: stats.totalSize,
            lastCleanup: stats.lastCleanup
        });
    } catch (error) {
        console.error('Error fetching deletion statistics:', error);
        res.status(500).json({
            error: 'Internal server error',
            message: error.message
        });
    }
});

// Manueller Cleanup-Trigger (für Testing)
router.post('/cleanup/trigger', async (req, res) => {
    try {
        console.log('[Admin API] Manual cleanup triggered');
        const result = await cleanupService.performScheduledCleanup();
        
        res.json({
            success: true,
            result: result,
            message: `Cleanup completed: ${result.deletedGroups} groups deleted`
        });
    } catch (error) {
        console.error('[Admin API] Error triggering cleanup:', error);
        res.status(500).json({
            error: 'Internal server error',
            message: error.message
        });
    }
});

// Zeige welche Gruppen gelöscht würden (Dry-Run)
router.get('/cleanup/preview', async (req, res) => {
    try {
        const groups = await cleanupService.findGroupsForDeletion();
        
        // Berechne Tage bis zur Löschung für jede Gruppe
        const groupsWithDays = groups.map(group => ({
            ...group,
            daysUntilDeletion: cleanupService.getDaysUntilDeletion(group.uploadDate)
        }));

        res.json({
            success: true,
            groupsToDelete: groupsWithDays.length,
            groups: groupsWithDays,
            message: groupsWithDays.length === 0 
                ? 'No groups would be deleted' 
                : `${groupsWithDays.length} groups would be deleted`
        });
    } catch (error) {
        console.error('[Admin API] Error previewing cleanup:', error);
        res.status(500).json({
            error: 'Internal server error',
            message: error.message
        });
    }
});


module.exports = router;
