import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Keys that can be read/written via the API
const ALLOWED_KEYS = [
    'AWS_ACCESS_KEY_ID',
    'AWS_SECRET_ACCESS_KEY',
    'AWS_REGION',
    'SES_FROM_EMAIL',
    'SES_RATE_LIMIT',
    'SERVER_URL',
    'PORT',
    'CORS_ORIGIN',
    'NODE_ENV',
];
// Keys whose values should be masked in GET responses
const SECRET_KEYS = new Set([
    'AWS_ACCESS_KEY_ID',
    'AWS_SECRET_ACCESS_KEY',
]);
function getEnvPath() {
    return process.env.DOTENV_PATH ?? path.resolve(__dirname, '..', '..', '..', '.env');
}
function parseEnvFile(filePath) {
    const entries = new Map();
    if (!fs.existsSync(filePath))
        return entries;
    const content = fs.readFileSync(filePath, 'utf-8');
    for (const line of content.split('\n')) {
        const trimmed = line.trim();
        if (!trimmed || trimmed.startsWith('#'))
            continue;
        const eqIndex = trimmed.indexOf('=');
        if (eqIndex === -1)
            continue;
        const key = trimmed.slice(0, eqIndex).trim();
        const value = trimmed.slice(eqIndex + 1).trim();
        entries.set(key, value);
    }
    return entries;
}
function writeEnvFile(filePath, entries) {
    const lines = [];
    for (const [key, value] of entries) {
        lines.push(`${key}=${value}`);
    }
    fs.writeFileSync(filePath, lines.join('\n') + '\n', 'utf-8');
}
function maskValue(key, value) {
    if (!SECRET_KEYS.has(key))
        return value;
    if (value.length <= 4)
        return '****';
    return '****' + value.slice(-4);
}
export async function settingsRoutes(app, _opts) {
    // GET /api/settings/env — returns allowed env vars (secrets masked)
    app.get('/api/settings/env', { preHandler: [app.requireAuth, app.requireRole('admin')] }, async () => {
        const envPath = getEnvPath();
        const entries = parseEnvFile(envPath);
        const result = {};
        for (const key of ALLOWED_KEYS) {
            const value = entries.get(key) ?? '';
            result[key] = maskValue(key, value);
        }
        return { settings: result };
    });
    // PATCH /api/settings/env — updates allowed env vars
    app.patch('/api/settings/env', { preHandler: [app.requireAuth, app.requireRole('admin')] }, async (request, reply) => {
        const updates = request.body;
        const invalidKeys = Object.keys(updates).filter(k => !ALLOWED_KEYS.includes(k));
        if (invalidKeys.length > 0) {
            return reply.code(400).send({ error: `Invalid keys: ${invalidKeys.join(', ')}` });
        }
        const envPath = getEnvPath();
        const entries = parseEnvFile(envPath);
        for (const [key, value] of Object.entries(updates)) {
            if (value === '') {
                entries.delete(key);
            }
            else {
                entries.set(key, value);
            }
            // Also update process.env so the running server picks up changes
            if (value === '') {
                delete process.env[key];
            }
            else {
                process.env[key] = value;
            }
        }
        writeEnvFile(envPath, entries);
        // Return the updated settings (masked)
        const result = {};
        for (const key of ALLOWED_KEYS) {
            const value = entries.get(key) ?? '';
            result[key] = maskValue(key, value);
        }
        return { settings: result };
    });
}
// Exported for testing
export { ALLOWED_KEYS, SECRET_KEYS, parseEnvFile, writeEnvFile, maskValue };
//# sourceMappingURL=settings-routes.js.map