import { readFileSync, existsSync } from 'fs';
import { resolve } from 'path';
import { json, error } from '@sveltejs/kit';
import { readCachedEmbyUsers, writeCachedEmbyUsers } from '../../../lib/server/emby-user-cache.js';

const CONFIG_PATH = resolve('config.json');

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

export async function GET() {
	const { embyUrl, apiKey } = loadConfig();
	if (!embyUrl || !apiKey) {
		throw error(400, 'Emby URL and API key not configured');
	}

	const base = embyUrl.replace(/\/+$/, '');
	let res;
	try {
		res = await fetch(`${base}/Users?api_key=${encodeURIComponent(apiKey)}`);
	} catch (e) {
		const cached = readCachedEmbyUsers();
		if (cached.users.length > 0) {
			return json({
				users: cached.users,
				source: 'cache',
				lastSyncedAt: cached.lastSyncedAt,
				message: `Using cached Emby users because the server could not be reached: ${e.message}`
			});
		}
		throw error(502, `Could not reach Emby server: ${e.message}`);
	}

	if (!res.ok) {
		if (res.status >= 500) {
			const cached = readCachedEmbyUsers();
			if (cached.users.length > 0) {
				return json({
					users: cached.users,
					source: 'cache',
					lastSyncedAt: cached.lastSyncedAt,
					message: `Using cached Emby users because the Emby API returned ${res.status} ${res.statusText}`
				});
			}
		}
		throw error(res.status, `Emby API error: ${res.status} ${res.statusText}`);
	}

	const users = await res.json();
	const cached = writeCachedEmbyUsers(
		users.map((u) => ({
			embyGuid: u.Id,
			name: u.Name
		}))
	);

	return json({
		users: cached.users,
		source: 'live',
		lastSyncedAt: cached.lastSyncedAt
	});
}
