import { analytics } from "@ax/api";
import { appActions } from "@ax/containers/App";
import { handleRequest } from "@ax/helpers";
import { IAnalytics } from "@ax/types";
import { Dispatch } from "redux";
import { SET_ANALYTICS } from "./constants";
import { ISetAnalytics } from "./interfaces";

function setAnalytics(analytics: IAnalytics): ISetAnalytics {
	return { type: SET_ANALYTICS, payload: analytics };
}

function getAnalytics(siteId?: number | null): (dispatch: Dispatch) => Promise<void> {
	return async (dispatch) => {
		try {
			const callback = async () => analytics.getAnalytics(siteId || "global");

			const responseActions = {
				handleSuccess: (response: any) => {
					dispatch(setAnalytics(response));
				},
				handleError: (response: any) => appActions.handleError(response)(dispatch),
			};

			await handleRequest(callback, responseActions, [])(dispatch);
		} catch (e) {
			console.log(e);
		}
	};
}

function updateAnalytics(analyticsState: IAnalytics, siteId?: number | null): (dispatch: Dispatch) => Promise<boolean> {
	return async (dispatch) => {
		try {
			const { scriptCode, dimensions, groups } = analyticsState;
			const callback = async () => {
				const promises = [];
				const site = siteId || "global";
				promises.push(analytics.updateScriptCode(site, { scriptCode }));
				promises.push(analytics.createDimensions(site, { dimensions }));
				promises.push(analytics.createDimensionsGroups(site, { groups }));
				return Promise.all(promises);
			};

			const responseActions = {
				handleSuccess: () => {
					getAnalytics(siteId)(dispatch);
				},
				handleError: (response: any) => {
					const {
						data: { message },
					} = response;
					const isMultiple = Array.isArray(message) && message.length > 1;
					const msg = isMultiple ? `The action failed due to ${message.length} errors.` : undefined;
					appActions.handleError(response, isMultiple, msg)(dispatch);
				},
			};

			return await handleRequest(callback, responseActions, [appActions.setIsSaving])(dispatch);
		} catch (e) {
			console.log(e);
			return false;
		}
	};
}

function updateScriptCode(scriptCode: string, siteId?: number | null): (dispatch: Dispatch) => Promise<boolean> {
	return async (dispatch) => {
		try {
			const callback = async () => {
				return analytics.updateScriptCode(siteId || "global", { scriptCode });
			};

			const responseActions = {
				handleSuccess: () => {
					getAnalytics(siteId)(dispatch);
				},
				handleError: (response: any) => appActions.handleError(response)(dispatch),
			};

			return await handleRequest(callback, responseActions, [appActions.setIsSaving])(dispatch);
		} catch (e) {
			console.log(e);
			return false;
		}
	};
}

function deleteScriptCode(siteId?: number | null): (dispatch: Dispatch) => Promise<boolean> {
	return async (dispatch) => {
		try {
			const callback = async () => analytics.deleteScriptCode(siteId || "global");

			const responseActions = {
				handleSuccess: () => {
					getAnalytics(siteId)(dispatch);
				},
				handleError: (response: any) => appActions.handleError(response)(dispatch),
			};

			return await handleRequest(callback, responseActions, [])(dispatch);
		} catch (e) {
			console.log(e);
			return false;
		}
	};
}

export { setAnalytics, getAnalytics, updateAnalytics, updateScriptCode, deleteScriptCode };
