import { template } from "./config";
import { type IServiceConfig, sendRequest } from "./utils";

const SERVICES: { [key: string]: IServiceConfig } = {
	GET_SITE_ITEMS: {
		...template,
		endpoint: "/select/site/",
		method: "GET",
	},
	GET_ITEMS: {
		...template,
		endpoint: "/select",
		method: "GET",
	},
	GET_SITES: {
		...template,
		endpoint: "/select/sites",
		method: "GET",
	},
};

const getSelectSiteItems = async (
	siteId: number,
	entity: string,
	params?: Record<string, any>,
	pageID?: number,
	forceLanguage?: number,
) => {
	const { host, endpoint } = SERVICES.GET_SITE_ITEMS;

	let urlParams = "";
	if (params) {
		for (const prop in params) {
			urlParams = `${urlParams}${prop}=${params[prop]}&`;
		}
		urlParams = urlParams.length ? `?${urlParams.slice(0, -1)}` : "";
	}

	SERVICES.GET_SITE_ITEMS.dynamicUrl = pageID
		? `${host}${endpoint}${siteId}/${entity}/${pageID}${urlParams}`
		: `${host}${endpoint}${siteId}/${entity}${urlParams}`;

	const headers = forceLanguage ? { lang: forceLanguage } : undefined;
	return sendRequest(SERVICES.GET_SITE_ITEMS, undefined, headers);
};

const getSelectItems = async (entity: string, entityId?: number | string, lang?: number) => {
	const { host, endpoint } = SERVICES.GET_ITEMS;
	const filter = lang ? `?filterByLanguage=${lang}` : "";
	SERVICES.GET_ITEMS.dynamicUrl = entityId
		? `${host}${endpoint}/${entity}/${entityId}${filter}`
		: `${host}${endpoint}/${entity}${filter}`;

	return sendRequest(SERVICES.GET_ITEMS);
};

const getSelectSites = async (lang?: number) => {
	const { host, endpoint } = SERVICES.GET_SITES;
	const filter = lang ? `?filterByLanguage=${lang}` : "";
	SERVICES.GET_ITEMS.dynamicUrl = `${host}${endpoint}${filter}`;

	return sendRequest(SERVICES.GET_SITES);
};

export default { getSelectSiteItems, getSelectItems, getSelectSites };
