import promiseProps from '../../utils/promise-props.js';
import slugify from '../../utils/slugify.js';
import { getIdsBySlug } from '../cache.js';
import { HttpError } from '../errors.js';
import { fetchMovies, fetchMoviesById } from '../movies.js';
import { parseActorIdentifier } from '../query.js';
import { fetchStashByUsernameAndSlug } from '../stashes.js';

export async function curateMoviesQuery(query) {
	return {
		scope: query.scope || 'latest',
		query: query.q,
		years: query.years?.split(',')?.map((year) => Number(year)).filter(Boolean) || [],
		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,
		stashId: Number(query.stashId) || null,
	};
}

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

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

export async function fetchMovieApi(req, res) {
	const [movie] = await fetchMoviesById([Number(req.params.movieId)], { reqUser: req.user }, { restriction: req.geo.restriction });

	if (!movie) {
		throw new HttpError(`No movie with ID ${req.params.movieId} found`, 404);
	}

	res.send(movie);
}

export const moviesSchema = `
	extend type Query {
		movies(
			query: String
			scope: String
			entities: [String!]
			actorIds: [String!]
			tags: [String!]
			stash: String
			limit: Int! = 30
			page: Int! = 1
		): ReleasesResult

		movie(
			id: Int!
		): Release

		moviesById(
			ids: [Int!]!
		): [Release]
	}
`;

function getScope(query) {
	if (query.scope) {
		return query.scope;
	}

	if (query.query) {
		return 'results';
	}

	if (query.stash) {
		return 'stashed';
	}

	return 'latest';
}

export async function fetchMoviesGraphql(query, req) {
	const mainEntity = query.entities?.find((entity) => entity.charAt(0) !== '!');

	const stash = query.stash && req.user
		? await fetchStashByUsernameAndSlug(req.user.id, query.stash, req.user)
		: null;

	if (query.stash && !stash) {
		throw new HttpError(`Could not find stash '${query.stash}'`, 404);
	}

	const {
		tagIds,
		notTagIds,
		entityId,
		notEntityIds,
	} = await promiseProps({
		tagIds: getIdsBySlug(query.tags?.filter((tag) => tag.charAt(0) !== '!'), 'tags'),
		notTagIds: getIdsBySlug(query.tags?.filter((tag) => tag.charAt(0) === '!').map((tag) => tag.slice(1)).map((tag) => slugify(tag)), 'tags'),
		entityId: getIdsBySlug([mainEntity], 'entities').then(([id]) => id),
		notEntityIds: getIdsBySlug(query.entities?.filter((entity) => entity.charAt(0) === '!').map((entity) => entity.slice(1)), 'entities'),
	});

	const {
		movies,
		total,
	} = await fetchMovies({
		query: query.query, // query query query query
		tagIds,
		// not- currently not implemented by movies module, pass here anyway for when it is
		notTagIds,
		entityId,
		notEntityIds,
		actorIds: query.actorIds?.filter((actorId) => actorId.charAt(0) !== '!').map((actorId) => Number(actorId)),
		notActorIds: query.actorIds?.filter((actorId) => actorId.charAt(0) === '!').map((actorId) => Number(actorId.slice(1))),
		stashId: stash?.id,
		scope: getScope(query),
		isShowcased: null,
	}, {
		page: query.page || 1,
		limit: query.limit || 30,
		aggregate: false,
	}, req.user, { restriction: req.geo.restriction });

	return {
		nodes: movies,
		total,
	};
}

export async function fetchMoviesByIdGraphql(query, req) {
	const movies = await fetchMoviesById([].concat(query.id, query.ids).filter(Boolean), req.user);

	if (query.ids) {
		return movies;
	}

	return movies[0];
}
