import { error, json } from '@sveltejs/kit';
import { fetchEmbyJson, normalizeEmbyGuid } from '../../../lib/server/emby-api.js';
import { normalizeLookupItem } from '../../../lib/collection-tools.js';

export async function GET({ url }) {
	const userId = normalizeEmbyGuid(url.searchParams.get('userId'));
	const term = String(url.searchParams.get('term') || '').trim();
	const limit = Math.min(Math.max(Number(url.searchParams.get('limit') || 12), 1), 50);
	const types = (url.searchParams.get('types') || '')
		.split(',')
		.map((value) => value.trim())
		.filter(Boolean);

	if (!userId) {
		throw error(400, 'Missing userId');
	}

	if (!term) {
		return json({ items: [] });
	}

	try {
		const payload = await fetchEmbyJson(`/Users/${encodeURIComponent(userId)}/Items`, {
			params: {
				Recursive: true,
				SearchTerm: term,
				Limit: limit,
				SortBy: 'SortName',
				SortOrder: 'Ascending',
				Fields: 'Overview,Genres,ProviderIds,ProductionYear',
				IncludeItemTypes: types.join(','),
				GroupItemsIntoCollections: false
			}
		});

		return json({
			items: (payload.Items || payload || []).map(normalizeLookupItem)
		});
	} catch (err) {
		if (String(err.message || '').includes('not configured')) {
			throw error(400, err.message);
		}
		throw error(502, `Could not search Emby items: ${err.message}`);
	}
}
