const GroupRepository = require('../repositories/GroupRepository');
const DeletionLogRepository = require('../repositories/DeletionLogRepository');
const fs = require('fs').promises;
const path = require('path');

class GroupCleanupService {
    constructor() {
        this.CLEANUP_DAYS = 7; // Gruppen älter als 7 Tage werden gelöscht
    }

    // Findet alle Gruppen, die gelöscht werden müssen
    async findGroupsForDeletion() {
        try {
            const groups = await GroupRepository.findUnapprovedGroupsOlderThan(this.CLEANUP_DAYS);
            console.log(`[Cleanup] Found ${groups.length} groups for deletion (older than ${this.CLEANUP_DAYS} days)`);
            return groups;
        } catch (error) {
            console.error('[Cleanup] Error finding groups for deletion:', error);
            throw error;
        }
    }

    // Löscht eine Gruppe vollständig (DB + Dateien)
    async deleteGroupCompletely(groupId) {
        try {
            console.log(`[Cleanup] Starting deletion of group: ${groupId}`);

            // Hole Statistiken vor Löschung
            const stats = await GroupRepository.getGroupStatistics(groupId);
            if (!stats) {
                console.warn(`[Cleanup] Group ${groupId} not found, skipping`);
                return null;
            }

            // Lösche Gruppe aus DB (CASCADE löscht Bilder automatisch)
            const deleteResult = await GroupRepository.deleteGroupCompletely(groupId);

            // Lösche physische Dateien
            const deletedFiles = await this.deletePhysicalFiles(deleteResult.imagePaths);

            console.log(`[Cleanup] Deleted group ${groupId}: ${deletedFiles.success} files deleted, ${deletedFiles.failed} failed`);

            // Erstelle Deletion Log
            await this.logDeletion({
                ...stats,
                deletedFiles: deletedFiles
            });

            return {
                groupId: groupId,
                imagesDeleted: deleteResult.deletedImages,
                filesDeleted: deletedFiles.success
            };
        } catch (error) {
            console.error(`[Cleanup] Error deleting group ${groupId}:`, error);
            throw error;
        }
    }

    // Löscht physische Dateien (Bilder + Previews)
    async deletePhysicalFiles(imagePaths) {
        const dataDir = path.join(__dirname, '../data');
        let successCount = 0;
        let failedCount = 0;

        for (const image of imagePaths) {
            // Lösche Original-Bild
            if (image.file_path) {
                const fullPath = path.join(dataDir, image.file_path);
                try {
                    await fs.unlink(fullPath);
                    successCount++;
                } catch (error) {
                    if (error.code !== 'ENOENT') { // Ignoriere "Datei nicht gefunden"
                        console.warn(`[Cleanup] Failed to delete file: ${fullPath}`, error.message);
                        failedCount++;
                    }
                }
            }

            // Lösche Preview-Bild
            if (image.preview_path) {
                const previewPath = path.join(dataDir, image.preview_path);
                try {
                    await fs.unlink(previewPath);
                    successCount++;
                } catch (error) {
                    if (error.code !== 'ENOENT') {
                        console.warn(`[Cleanup] Failed to delete preview: ${previewPath}`, error.message);
                        failedCount++;
                    }
                }
            }
        }

        return {
            success: successCount,
            failed: failedCount
        };
    }

    // Erstellt Eintrag im Deletion Log
    async logDeletion(groupData) {
        try {
            await DeletionLogRepository.createDeletionEntry({
                groupId: groupData.groupId,
                year: groupData.year,
                imageCount: groupData.imageCount,
                uploadDate: groupData.uploadDate,
                deletionReason: 'auto_cleanup_7days',
                totalFileSize: groupData.totalFileSize
            });
            console.log(`[Cleanup] Logged deletion of group ${groupData.groupId}`);
        } catch (error) {
            console.error('[Cleanup] Error logging deletion:', error);
            // Nicht werfen - Deletion Log ist nicht kritisch
        }
    }

    // Hauptmethode: Führt kompletten Cleanup durch
    async performScheduledCleanup() {
        const startTime = Date.now();
        console.log('');
        console.log('========================================');
        console.log('[Cleanup] Starting scheduled cleanup...');
        console.log(`[Cleanup] Date: ${new Date().toISOString()}`);
        console.log('========================================');

        try {
            const groupsToDelete = await this.findGroupsForDeletion();

            if (groupsToDelete.length === 0) {
                console.log('[Cleanup] No groups to delete. Cleanup complete.');
                console.log('========================================');
                return {
                    success: true,
                    deletedGroups: 0,
                    message: 'No groups to delete'
                };
            }

            let successCount = 0;
            let failedCount = 0;

            for (const group of groupsToDelete) {
                try {
                    await this.deleteGroupCompletely(group.group_id);
                    successCount++;
                } catch (error) {
                    console.error(`[Cleanup] Failed to delete group ${group.group_id}:`, error);
                    failedCount++;
                }
            }

            const duration = ((Date.now() - startTime) / 1000).toFixed(2);
            console.log('');
            console.log(`[Cleanup] Cleanup complete!`);
            console.log(`[Cleanup] Deleted: ${successCount} groups`);
            console.log(`[Cleanup] Failed: ${failedCount} groups`);
            console.log(`[Cleanup] Duration: ${duration}s`);
            console.log('========================================');

            return {
                success: true,
                deletedGroups: successCount,
                failedGroups: failedCount,
                duration: duration
            };
        } catch (error) {
            console.error('[Cleanup] Scheduled cleanup failed:', error);
            console.log('========================================');
            throw error;
        }
    }

    // Berechnet verbleibende Tage bis zur Löschung
    getDaysUntilDeletion(uploadDate) {
        const upload = new Date(uploadDate);
        const deleteDate = new Date(upload);
        deleteDate.setDate(deleteDate.getDate() + this.CLEANUP_DAYS);
        
        const now = new Date();
        const diffTime = deleteDate - now;
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        return Math.max(0, diffDays);
    }
}

module.exports = new GroupCleanupService();
