import { readFileSync, writeFileSync, existsSync } from 'fs';
import { resolve } from 'path';
import { json } from '@sveltejs/kit';

const CONFIG_PATH = resolve('config.json');
const DEFAULT_CONFIG = { embyUrl: '', apiKey: '', tmdbApiKey: '', dbPath: '' };

function loadConfig() {
	if (!existsSync(CONFIG_PATH)) return DEFAULT_CONFIG;
	try {
		return {
			...DEFAULT_CONFIG,
			...JSON.parse(readFileSync(CONFIG_PATH, 'utf-8'))
		};
	} catch {
		return DEFAULT_CONFIG;
	}
}

export async function GET() {
	return json(loadConfig());
}

export async function POST({ request }) {
	const body = await request.json();
	const config = {
		embyUrl: String(body.embyUrl || '').trim(),
		apiKey: String(body.apiKey || '').trim(),
		tmdbApiKey: String(body.tmdbApiKey || '').trim(),
		dbPath: String(body.dbPath || '').trim()
	};
	writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));
	return json({ ok: true });
}
