import { censor } from '#/src/censor.js';
import { fetchTags, fetchTagsById } from '#/src/tags.js';

const tagSlugs = {
	popular: [
		'anal',
		'lesbian',
		// 'interracial',
		'threesome',
		// 'teen',
		'milf',
		'blowjob',
		'gay',
		'transsexual',
		'dp',
		'gangbang',
		'facial',
		'creampie',
		'squirting',
	],
	appearance: [
		'asian',
		'black',
		'latina',
		'white',
		'natural-tits',
		'fake-tits',
		'blonde',
		'brunette',
		'redhead',
		'tattoos',
		'piercings',
	],
	lgbt: [
		'lesbian',
		'gay',
		'bisexual',
		'transsexual',
	],
	oral: [
		'blowjob',
		'deepthroat',
		'facefucking',
		'pussy-eating',
		'ass-eating',
		'69',
		'atm',
	],
	group: [
		'threesome',
		'mfm',
		'mff',
		'orgy',
		'gangbang',
		'blowbang',
	],
	cumshot: [
		'facial',
		'bukkake',
		'creampie',
		'anal-creampie',
		'oral-creampie',
		'cum-in-mouth',
		'cum-on-boobs',
		'cum-on-butt',
		'cum-on-pussy',
		'fake-cum',
	],
	roleplay: [
		'family',
		'parody',
		'schoolgirl',
		'nurse',
		'maid',
	],
	penetration: [
		'dp',
		'airtight',
		'dap',
		'dvp',
		'triple-penetration',
		'tap',
		'tvp',
	],
	fetish: [
		'bdsm',
		'femdom',
		'bondage',
		'free-use',
		'latex',
		'blindfold',
	],
	manual: [
		'handjob',
		'fingering',
		'anal-fingering',
		'titty-fucking',
		'fisting',
		'anal-fisting',
	],
	toys: [
		'toys',
		'toy-anal',
		'toy-dp',
		'double-dildo',
		'double-dildo-blowjob',
		'double-dildo-kiss',
		'double-dildo-anal',
		'double-dildo-dp',
	],
	misc: [
		'gaping',
		'squirting',
		'oil',
		'vr',
		'bts',
	],
};

async function searchTags(pageContext) {
	const tags = await fetchTags({ query: pageContext.urlParsed.search.q }, { restriction: pageContext.geo.restriction });

	return {
		pageContext: {
			title: 'Tags',
			pageProps: {
				tagShowcase: {
					results: tags,
				},
			},
		},
	};
}

export async function onBeforeRender(pageContext) {
	if (pageContext.urlParsed.search.q) {
		return searchTags(pageContext);
	}

	const tags = await fetchTagsById(Object.values(tagSlugs).flat(), {}, pageContext.user, { restriction: pageContext.geo.restriction });

	const filteredTags = tags.filter((tag) => !pageContext.tagFilter.includes(tag.name) && !pageContext.tagFilter.includes(tag.slug));
	const tagsBySlug = Object.fromEntries(filteredTags.map((tag) => [tag.slug, tag]));

	const tagShowcase = Object.fromEntries(Object.entries(tagSlugs).map(([category, categorySlugs]) => [
		censor(category, pageContext.geo.restriction),
		categorySlugs.map((slug) => tagsBySlug[slug]).filter(Boolean),
	]));

	return {
		pageContext: {
			title: 'Tags',
			pageProps: {
				tagShowcase,
			},
		},
	};
}
