const fs = require('fs');
const path = require('path');

// Store JSON metadata under data/db
const GROUPS_FILE = path.join(__dirname, '../data/db/upload-groups.json');

class GroupStorage {
    // Initialisiere die JSON-Datei falls sie nicht existiert
    static ensureDataFile() {
        const dataDir = path.dirname(GROUPS_FILE);
        if (!fs.existsSync(dataDir)) {
            fs.mkdirSync(dataDir, { recursive: true });
        }
        
        if (!fs.existsSync(GROUPS_FILE)) {
            fs.writeFileSync(GROUPS_FILE, JSON.stringify([], null, 2));
        }
    }
    
    // Alle Gruppen aus der JSON-Datei lesen
    static getAllGroups() {
        this.ensureDataFile();
        try {
            const data = fs.readFileSync(GROUPS_FILE, 'utf8');
            return JSON.parse(data);
        } catch (error) {
            console.error('Error reading groups file:', error);
            return [];
        }
    }
    
    // Einzelne Gruppe per ID finden
    static getGroup(groupId) {
        const groups = this.getAllGroups();
        return groups.find(group => group.groupId === groupId);
    }
    
    // Neue Gruppe speichern
    static saveGroup(group) {
        this.ensureDataFile();
        try {
            const groups = this.getAllGroups();
            groups.push(group.toJSON());
            fs.writeFileSync(GROUPS_FILE, JSON.stringify(groups, null, 2));
            return true;
        } catch (error) {
            console.error('Error saving group:', error);
            return false;
        }
    }
    
    // Gruppe löschen
    static deleteGroup(groupId) {
        try {
            const groups = this.getAllGroups();
            const filteredGroups = groups.filter(group => group.groupId !== groupId);
            fs.writeFileSync(GROUPS_FILE, JSON.stringify(filteredGroups, null, 2));
            return true;
        } catch (error) {
            console.error('Error deleting group:', error);
            return false;
        }
    }
    
    // Gruppen nach Datum sortiert abrufen (neueste zuerst)
    static getGroupsSorted() {
        const groups = this.getAllGroups();
        return groups.sort((a, b) => new Date(b.uploadDate) - new Date(a.uploadDate));
    }
}

module.exports = GroupStorage;