import { stringify } from '@brillout/json-serializer/stringify'; /* eslint-disable-line import/extensions */

import { fetchMovies } from '../movies.js';
import { parseActorIdentifier } from '../query.js';
import { getIdsBySlug } from '../cache.js';

export async function curateMoviesQuery(query) {
	return {
		scope: query.scope || 'latest',
		query: query.q,
		actorIds: [query.actorId, ...(query.actors?.split(',') || []).map((identifier) => parseActorIdentifier(identifier)?.id)].filter(Boolean),
		tagIds: await getIdsBySlug([query.tagSlug, ...(query.tags?.split(',') || [])], 'tags'),
		entityId: query.e ? await getIdsBySlug([query.e], 'entities').then(([id]) => id) : query.entityId,
		requireCover: query.cover,
	};
}

export async function fetchMoviesApi(req, res) {
	const {
		movies,
		aggActors,
		aggTags,
		aggChannels,
		limit,
		total,
	} = await fetchMovies(await curateMoviesQuery(req.query), {
		page: Number(req.query.page) || 1,
		limit: Number(req.query.limit) || 30,
	});

	res.send(stringify({
		movies,
		aggActors,
		aggTags,
		aggChannels,
		limit,
		total,
	}));
}
