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

const CONFIG_PATH = process.env.CONFIG_PATH || '/data/config.json';

function getEnvConfig() {
    return {
        adminPassword: process.env.ADMIN_PASSWORD || 'admin',
        baserowUrl: (process.env.BASEROW_URL || 'http://baserow:80').replace(/\/+$/, ''),
        baserowToken: process.env.BASEROW_TOKEN || '',
        port: parseInt(process.env.PORT || '7849', 10),
    };
}

function readConfig() {
    const defaults = { sets: [], answersTableId: null };
    try {
        if (fs.existsSync(CONFIG_PATH)) {
            return { ...defaults, ...JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) };
        }
    } catch (e) {
        console.error('[config] Fehler beim Lesen:', e.message);
    }
    return defaults;
}

function writeConfig(data) {
    const dir = path.dirname(CONFIG_PATH);
    if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
    fs.writeFileSync(CONFIG_PATH, JSON.stringify(data, null, 2), 'utf8');
}

module.exports = { getEnvConfig, readConfig, writeConfig };