export default function consentHandler(req, res, next) {
	const redirect = req.headers.referer && new URL(req.headers.referer).searchParams.get('redirect');

	if (Object.hasOwn(req.query, 'lgbt')) {
		const lgbtFilters = Array.from(new Set([...(req.tagFilter || []).filter((tag) => !['gay', 'bisexual', 'transsexual'].includes(tag)), 'extreme-insertion']));

		req.tagFilter = lgbtFilters;
		res.cookie('tags', JSON.stringify(lgbtFilters));
	}

	if (Object.hasOwn(req.query, 'straight')) {
		const straightFilters = Array.from(new Set([...(req.tagFilter || []), 'gay', 'bisexual', 'transsexual', 'extreme-insertion']));

		req.tagFilter = straightFilters;
		res.cookie('tags', JSON.stringify(straightFilters));
	}

	if (Object.hasOwn(req.query, 'consent')) {
		req.session.hasConsent = true;
		res.redirect(redirect || req.path);

		return;
	}

	if (!req.path.includes('/consent') && !req.session?.hasConsent) {
		res.redirect(`/consent?redirect=${req.originalUrl === '/' ? '' : encodeURIComponent(req.originalUrl)}`);

		return;
	}

	next();
}
