import { base_new_url } from "utilFuncs/utilFunctions";

const getPrefix = () => {
		return `${base_new_url()}/api/v2`;
	},
	prefix = getPrefix();

const APIPaths: Record<string, string> = {
	'news.index': '/news',
	'news.show': '/news/:slug',
	'classifieds.index': '/classifieds',
	'classifieds.show': '/classifieds/:slug',
	'ads.index': '/ads',
	'ads.show': '/ads/:slug',
};

interface APIRouteOptions {
	queryParams: Record<string, string>;
}

const api = (
	name: string,
	params?: Record<string, any>,
	options?: APIRouteOptions,
): string => {
	let theRoutePath: string = APIPaths[name];

	if (!theRoutePath) {
		throw new Error(`Cannot find API route with name ${name}`);
	}

	// let theRoutePath = theRoute.path;
	const paramNames: string[] = theRoutePath
		.split('/')
		.filter(segment => segment.includes(':'))
		.map(filteredSegment => filteredSegment.replace(':', ''));

	// determine if path contains params
	if (paramNames.length) {
		// ensure params object is set
		if (!params) {
			throw new Error(
				`The route with name '${name}' requires the following parameters [${paramNames.join(
					', ',
				)}]`,
			);
		}

		// ensure all params in pathnames are
		// defined in params object prop
		paramNames.forEach(paramName => {
			if (!Object.keys(params).includes(paramName))
				throw new Error(
					`The route '${name}' expected '${paramName}' to be present in params object`,
				);

			if (params[paramName] !== null && !params[paramName])
				throw new Error(
					`The value of '${paramName}' is empty. If this parameter really should be empty, set it to 'null' instead.`,
				);
		});

		// replace param names with
		// matching values from params
		// object prop
		Object.entries(params).forEach(([key, value]) => {
			theRoutePath = theRoutePath.replace(`:${key}`, value.toString());
		});
	}

	if (options?.queryParams) {
		return (
			prefix +
			theRoutePath +
			'?' +
			Object.entries(options.queryParams)
				.map(([key, value]) => `${key}=${value}`)
				.join('&&')
		);
	}
	return prefix + theRoutePath;
};

export default api;
