let expectedPendingRequestsCount = 0;
let pendingRequests = [];
let pendingStrategyIds = [];

const ApiRoutes = {
	TradingConditions: {
		Create: "/api/tradingConditions",
		Delete: "/api/tradingConditions/{id}",
		Bulk: "/api/tradingConditions/bulk",
	},
	Logs: "/api/logs",
	Instruments: "/api/instruments/{symbolRoot}",
};

const ClientMessages = {
	FAILED_TO_CREATE_TRADING_CONDITION: "新增條件單失敗",
	FAILED_TO_DELETE_TRADING_CONDITION: "刪除條件單失敗",
	FAILED_TO_GET_CONTRACT_MONTHS: "無法取得合約月份資料",
	FAILED_TO_SEND_LOG: "傳送日誌失敗!",
	FAILED_TO_CREATE_TRADING_CONDITIONS: "啟動全部條件單失敗",
	CREATE_TRADING_CONDITIONS_SUCCESS: "啟動全部條件單成功",
	FAILED_TO_DELETE_TRADING_CONDITIONS: "停用全部條件單失敗",
	DELETE_TRADING_CONDITIONS_SUCCESS: "停用全部條件單成功",
};

const DEFAULT_HEADERS = {
	Authorization: `Bearer ${accessToken}`,
	"Content-Type": "application/json",
};

const InternalApiClient = {
	createTradingCondition: (request) => {
		const requestUrl = `${currentUrl}${ApiRoutes.TradingConditions.Create}`;

		fetch(requestUrl, {
			method: "POST",
			headers: DEFAULT_HEADERS,
			body: JSON.stringify(request),
		})
			.then((response) => {
				if (!response.ok) {
					document.getElementById(`IsActivated-${request.strategyId}`).checked =
						false;

					return response.json().then((data) => {
						alert(
							`${ClientMessages.FAILED_TO_CREATE_TRADING_CONDITION}: ${data.title} - ${data.detail} UserId: ${userId} IP: ${clientIp} Origin: ${origin}`,
						);
					});
				}
				StrategyControlPane.disableFields(request.strategyId);
				refresh();
			})
			.catch((error) => {
				document.getElementById(`IsActivated-${request.strategyId}`).checked =
					false;

				alert(
					`${ClientMessages.FAILED_TO_CREATE_TRADING_CONDITION}: ${error} UserId: ${userId} IP: ${clientIp} Origin: ${origin}`,
				);
			});
	},

	deleteTradingCondition: (strategyId, conditionId) => {
		const requestUrl =
			`${currentUrl}${ApiRoutes.TradingConditions.Delete}`.replace(
				"{id}",
				conditionId,
			);

		fetch(requestUrl, {
			method: "DELETE",
			headers: DEFAULT_HEADERS,
		})
			.then((response) => {
				if (!response.ok) {
					document.getElementById(`IsActivated-${strategyId}`).checked = true;
					return response.json().then((data) => {
						alert(
							`${ClientMessages.FAILED_TO_DELETE_TRADING_CONDITION}: ${data.title} - ${data.detail}`,
						);
					});
				}
				StrategyControlPane.enableFields(strategyId);
				refresh();
			})
			.catch((error) => {
				document.getElementById(`IsActivated-${strategyId}`).checked = true;
				alert(`${ClientMessages.FAILED_TO_DELETE_TRADING_CONDITION}: ${error}`);
			});
	},

	listContractMonths: (symbolRoot, onSuccess) => {
		const requestUrl = `${currentUrl}${ApiRoutes.Instruments}`.replace(
			"{symbolRoot}",
			symbolRoot,
		);

		fetch(requestUrl).then((response) => {
			if (!response.ok) {
				return response.json().then((err) => {
					alert(
						`${ClientMessages.FAILED_TO_GET_CONTRACT_MONTHS}: ${err.title} - ${err.detail}`,
					);
				});
			}

			return response.json().then((data) => {
				if (!onSuccess) {
					return;
				}

				onSuccess(data);
			});
		});
	},

	sendLog: (level, message) => {
		const logHandlerMapping = {
			INF: console.log,
			WRN: console.warn,
			ERR: console.error,
		};
		const requestUrl = `${currentUrl}${ApiRoutes.Logs}`;

		const outputMessage = `[${level}] ${message}`;

		const requestBody = JSON.stringify({
			message: outputMessage,
		});

		const consoleHandler = logHandlerMapping[level] || console.log;
		fetch(requestUrl, {
			method: "POST",
			headers: DEFAULT_HEADERS,
			body: requestBody,
		})
			.then((response) => {
				if (!response.ok) {
					console.error(ClientMessages.FAILED_TO_SEND_LOG);
				} else {
					consoleHandler(outputMessage);
				}
			})
			.catch((error) => {
				console.error(ClientMessages.FAILED_TO_SEND_LOG, error);
			});
	},

	bulkCreateTradingConditions: (requests) => {
		fetch(`${currentUrl}${ApiRoutes.TradingConditions.Bulk}`, {
			method: "POST",
			headers: DEFAULT_HEADERS,
			body: JSON.stringify({
				tradingConditions: requests,
			}),
		})
        .then((response) => {
            if (!response.ok) {
                return response.json().then((data) => {
                    Logger.logError(
                        `${ClientMessages.FAILED_TO_CREATE_TRADING_CONDITIONS}: ${data.title} - ${data.detail}`,
                    );
                    refresh();
                });
            }

            alert(ClientMessages.CREATE_TRADING_CONDITIONS_SUCCESS);
            refresh();
        })
        .catch((error) => {
            alert(
                `${ClientMessages.FAILED_TO_CREATE_TRADING_CONDITIONS}: ${error}`,
            );
            refresh();
        });
	},

	bulkDeleteTradingConditions: (conditionIds) => {
		fetch(`${currentUrl}${ApiRoutes.TradingConditions.Bulk}`, {
			method: "DELETE",
			headers: DEFAULT_HEADERS,
			body: JSON.stringify({ conditionIds }),
		}).then((response) => {
			if (!response.ok) {
				return response.json().then((data) => {
					alert(
						`${ClientMessages.FAILED_TO_DELETE_TRADING_CONDITIONS}: ${data.title} - ${data.detail}`,
					);
					refresh();
				});
			}

			alert(ClientMessages.DELETE_TRADING_CONDITIONS_SUCCESS);
			refresh();
		});
	},
};
