import { AxiosResponse } from "axios";
import { template } from "./config";
import { IServiceConfig, sendRequest } from "./utils";
import { LogActivityExportRequest, LogActivityPaginationRequest } from "@griddo/api-types";

const SERVICES: { [key: string]: IServiceConfig } = {
	GET_LOG_ACTIVITY: {
		...template,
		endpoint: "/logs/activity-timeline",
		method: "GET",
	},
	GET_LOG_ACTIVITY_BY_DAY: {
		...template,
		endpoint: "/logs/activity-grouped-day",
		method: "GET",
	},
	GET_LOG_ACTIVITY_BY_USER: {
		...template,
		endpoint: "/logs/activity-grouped-user",
		method: "GET",
	},
	GET_LOG_EVENT_TYPES: {
		...template,
		endpoint: "/logs/activity-events-type",
		method: "GET",
	},
	LOG_EXPORT: {
		...template,
		endpoint: "/logs/activity-timeline/export",
		method: "POST",
		responseType: "blob",
	},
};

const getLogActivityTimeline = async (params: LogActivityPaginationRequest): Promise<AxiosResponse> => {
	const { host, endpoint } = SERVICES.GET_LOG_ACTIVITY;

	const paramsUrl = new URLSearchParams();

	for (const [clave, valor] of Object.entries(params)) {
		if (valor !== undefined && valor !== null) {
			paramsUrl.append(clave, String(valor));
		}
	}

	SERVICES.GET_LOG_ACTIVITY.dynamicUrl = `${host}${endpoint}?${paramsUrl.toString()}`;

	return sendRequest(SERVICES.GET_LOG_ACTIVITY);
};

const getLogActivityTimelineByDay = async (params: LogActivityPaginationRequest): Promise<AxiosResponse> => {
	const { host, endpoint } = SERVICES.GET_LOG_ACTIVITY_BY_DAY;

	const paramsUrl = new URLSearchParams();

	for (const [clave, valor] of Object.entries(params)) {
		if (valor !== undefined && valor !== null) {
			paramsUrl.append(clave, String(valor));
		}
	}

	SERVICES.GET_LOG_ACTIVITY_BY_DAY.dynamicUrl = `${host}${endpoint}?${paramsUrl.toString()}`;

	return sendRequest(SERVICES.GET_LOG_ACTIVITY_BY_DAY);
};

const getLogActivityTimelineByUser = async (params: LogActivityPaginationRequest): Promise<AxiosResponse> => {
	const { host, endpoint } = SERVICES.GET_LOG_ACTIVITY_BY_USER;

	const paramsUrl = new URLSearchParams();

	for (const [clave, valor] of Object.entries(params)) {
		if (valor !== undefined && valor !== null) {
			paramsUrl.append(clave, String(valor));
		}
	}

	SERVICES.GET_LOG_ACTIVITY_BY_USER.dynamicUrl = `${host}${endpoint}?${paramsUrl.toString()}`;

	return sendRequest(SERVICES.GET_LOG_ACTIVITY_BY_USER);
};

const getLogActivityEventTypes = async (): Promise<AxiosResponse> => {
	return sendRequest(SERVICES.GET_LOG_EVENT_TYPES);
};

const logExport = async (data: LogActivityExportRequest): Promise<AxiosResponse> => {
	return sendRequest(SERVICES.LOG_EXPORT, { ...data });
};

export default {
	getLogActivityTimeline,
	getLogActivityTimelineByDay,
	getLogActivityTimelineByUser,
	getLogActivityEventTypes,
	logExport,
};
