import fs from 'fs';
import path from 'path';

const SETTINGS_DIR = path.join(process.cwd(), 'database');
const SETTINGS_FILE = path.join(SETTINGS_DIR, 'settings.json');

export interface AppSettings {
    activeSources: string[];
}

export function loadSettings(): AppSettings | null {
    try {
        if (!fs.existsSync(SETTINGS_FILE)) return null;
        const data = fs.readFileSync(SETTINGS_FILE, 'utf8');
        return JSON.parse(data);
    } catch (error: any) {
        console.error('[Settings] Erreur lors du chargement des paramètres:', error.message);
        return null;
    }
}

export function saveSettings(settings: Partial<AppSettings>) {
    try {
        if (!fs.existsSync(SETTINGS_DIR)) {
            fs.mkdirSync(SETTINGS_DIR, { recursive: true });
        }
        
        const currentSettings = loadSettings() || { activeSources: [] };
        const newSettings = { ...currentSettings, ...settings };
        
        fs.writeFileSync(SETTINGS_FILE, JSON.stringify(newSettings, null, 2), 'utf8');
    } catch (error: any) {
        console.error('[Settings] Erreur lors de la sauvegarde des paramètres:', error.message);
    }
}
