import { Router } from 'express';
import axios from 'axios';
import { CONSTANTS_BG, TEXT_CONSTANTS } from '../constants';
import { Ticker, PayType, OrderStatus, User } from '../models_nosql';
import { getSignature_BG } from '../utilities';
import {
	handlerTotalBalance,
	getMerchantOrders,
	getUserPayMethods,
	getMerchantAdvs,
	getArraySortedByProp,
	getArrayFilteredByProp,
	getOrderDetails,
	getTickerPriceUSDT,
	checkOrderInDB,
	insertOrderToDB,
	getP2POrders,
	getSpotOrders,
	getP2POrdersNomalized,
	getSpotOrdersNomalized,
	getMerchantAdvsNomalized,
	getMerchantOrdersNomalized,
	getBalancesNormalized,
	getPayMethodProps,
	getPayMethodPropsReverse,
	getPaySubAccount,
	getSingleUserProperty,
	consoleProcessed,
	getOrderDetailsNomalized,
	getObjectRequestParams,
} from '../common';
const {
	SHORT_NAME,
	BASE_URL,
	GET_SPOT_BALANCE,
	GET_SPOT_BALANCE_BY_API,
	GET_P2P_BALANCE,
	TRANSFER_ASSET_FROM_P2P,
	TRANSFER_ASSET_FROM_SPOT,
	GET_P2P_ORDERS,
	GET_P2P_ORDERS_BY_API,
	GET_MERCHANT_ORDERS,
	GET_MERCHANT_ORDERS_BY_API,
	GET_MERCHANT_ORDER_DETAILS,
	GET_MERCHANT_ADVS,
	GET_MERCHANT_ADVS_BY_API,
	CHANGE_STATUS_ADVS,
	GET_ADV_DETAIL,
	UPDATE_DETAILS_ADV,
	GET_HISTORY_SPOT_ORDERS,
	GET_HISTORY_SPOT_ORDERS_BY_API,
	GET_ACTIVE_SPOT_ORDERS,
	GET_ACTIVE_SPOT_ORDERS_BY_API,
	GET_MERCHANT_ADV_PAYMENTS,
	GET_MERCHANT_DETAILS,
} = CONSTANTS_BG;

export const ordersRouter_BG = Router();

// получение балансов
ordersRouter_BG.post('/get-balances', async (req, res) => {
	const { userId, exchangeId, shortName } = req.body;
	const user = await User.findOne({ _id: userId });

	const objParams = {
		userId,
		shortName,
		prefix: `balance_${shortName}_API`,
		apiKeys: getSingleUserProperty('apiKeys', exchangeId, user.properties),
		constants: CONSTANTS_BG,
		// requestHeader: {},
		additionals: { exchangeId },
	};

	const totalBalance = await handlerTotalBalance(objParams);

	return res.status(200).json({
		success: totalBalance.spotBalance.length === 0 ? false : true,
		balances: totalBalance,
		message:
			totalBalance.spotBalance.length === 0
				? `${shortName}: ${TEXT_CONSTANTS.BALANCE_ER}`
				: `${shortName}: ${TEXT_CONSTANTS.BALANCE_OK}`,
	});
});

// получение массива объявлений
ordersRouter_BG.post('/merchant-advs', async (req, res) => {
	const { userId, shortName, exchangeId } = req.body;
	const user = await User.findOne({ _id: userId });

	const objParamsAPI = {
		userId,
		prefix: `advs_${shortName}_API`,
		constants: CONSTANTS_BG,
		apiKeys: getSingleUserProperty('apiKeys', exchangeId, user.properties),
		// requestHeader,
		additionals: {},
	};

	const objReqParamsAPI = getObjectRequestParams(objParamsAPI);
	const arrData = await getMerchantAdvs(objReqParamsAPI);
	const arrPayTypes = await PayType.find();

	return res.status(200).json({
		success: arrData.length !== 0 ? true : false,
		data: {
			// merchantAdvs: [],
			merchantAdvs:
				arrData.length !== 0
					? getMerchantAdvsNomalized(
							arrData,
							{
								userId,
								exchangeId,
								prefix: shortName,
							},
							arrPayTypes
					  )
					: [],
			userPayMethods: [],
		},
		message:
			arrData.length !== 0
				? `${shortName}: ${TEXT_CONSTANTS.USER_ADVS_OK}`
				: `${shortName}: ${TEXT_CONSTANTS.USER_ADVS_ER}`,
	});
});

// изменение статуса объявления (-ий) мерчанта
ordersRouter_BG.post('/adv-status', async (req, res) => {
	res.status(400).json({
		error,
		message: `${SHORT_NAME}: ${TEXT_CONSTANTS.ADV_STATUS_ER}`,
	});
});

// получение редактируемого объявления мерчанта
ordersRouter_BG.post('/adv-edit', async (req, res) => {
	res.status(400).json({
		error,
		message: `${SHORT_NAME}: ${TEXT_CONSTANTS.ADV_EDIT_ER}`,
	});
});

// обновление редактируемого объявления
ordersRouter_BG.post('/adv-update', async (req, res) => {
	res.status(400).json({
		message: `${SHORT_NAME}: ${TEXT_CONSTANTS.ADV_UPDATE_ER}`,
	});
});

// получение массива p2p-ордеров стакана
ordersRouter_BG.post('/p2p', async (req, res) => {
	const { userId, exchangeId, shortName, objParams } = req.body;
	const { asset, fiat, arrPayments, sideType, page, amount } = objParams;

	const arrPayTypes = await PayType.find();
	const tradeType = sideType === 'BUY' ? 'SELL' : 'BUY';
	const paymentIdx =
		arrPayments.length === 0
			? ['']
			: arrPayments.map((item, index) => {
					return getPayMethodPropsReverse(
						exchangeId,
						'payId', // payId or payName
						item, // internalPayMethod
						arrPayTypes
					);
			  });
	const user = await User.findOne({ _id: userId });

	const apiKeys = getSingleUserProperty(
		'apiKeys',
		exchangeId,
		user.properties
	);

	const endTime = new Date().getTime();
	const startTime = endTime - 60000 * 60 * 24 * 600; // 60 days ago

	const method = GET_P2P_ORDERS_BY_API.method;
	const requestPath = GET_P2P_ORDERS_BY_API.url;
	const query_string = `?online=yes&pageSize=29`;
	const final_string = `${endTime}${method}${requestPath}${query_string}`;
	const signParams = getSignature_BG(final_string, apiKeys);

	const params = {
		prefix: `${shortName}_API`,
		config: {
			withCredentials: true,
			method,
			url: `${BASE_URL}${requestPath}${query_string}`,
			// data: null, // data: {} - only POST requests
			headers: {
				'ACCESS-KEY': `${signParams.publicKey}`,
				'ACCESS-SIGN': `${signParams.signature}`,
				'ACCESS-TIMESTAMP': `${endTime}`,
				'ACCESS-PASSPHRASE': `${signParams.passPhrase}`,
				locale: 'en-US',
				'Content-Type': 'application/json',
			},
		},
	};

	const arrData = await getP2POrders(params);
	// console.log(arrData.length);
	return res.status(200).json({
		success: arrData.length !== 0 ? true : false,
		data: {
			p2pOrders: [],
			// p2pOrders:
			// 	arrData.length !== 0
			// 		? getP2POrdersNomalized(
			// 				arrDataSorted,
			// 				{
			// 					userId,
			// 					exchangeId,
			// 					prefix: shortName,
			// 				},
			// 				arrPayTypes
			// 		  )
			// 		: [],
			tickers: await Ticker.find(),
		},
		message:
			arrData.length !== 0
				? `${shortName}: ${arrData.length} ${TEXT_CONSTANTS.P2P_ORDERS_OK}`
				: `${shortName}: ${TEXT_CONSTANTS.P2P_ORDERS_ER}`,
	});
});

// получение массива текущих merchant-ордеров
ordersRouter_BG.post('/merchant-orders', async (req, res) => {
	const { userId, exchangeId, shortName } = req.body;
	const arrTickers = await Ticker.find();
	let status = 200;

	const user = await User.findOne({ _id: userId });
	const apiKeys = getSingleUserProperty(
		'apiKeys',
		exchangeId,
		user.properties
	);

	const objParams = {
		userId,
		prefix: `otc_${shortName}_API`,
		apiKeys,
		constants: CONSTANTS_BG,
		// requestHeader: {},
		// additionals: {},
	};

	const objReqParamsAPI = getObjectRequestParams(objParams);
	const arrData = await getMerchantOrders(objReqParamsAPI);
	const arrPayTypes = await PayType.find();
	const arrOrderStatus = await OrderStatus.find();

	return res.status(status).json({
		success: arrData.length !== 0 ? true : false,
		// data: [],
		data:
			arrData.length !== 0
				? getMerchantOrdersNomalized(
						arrData,
						{
							userId,
							exchangeId,
							prefix: `${shortName}`,
						},
						arrPayTypes,
						arrOrderStatus
				  )
				: [],
		message:
			arrData.length !== 0
				? `${shortName}: ${arrData.length} ${TEXT_CONSTANTS.USER_ORDERS_OK}`
				: `${shortName}: ${TEXT_CONSTANTS.USER_ORDERS_ER}`,
	});
});

// получение сведений об мерчанте и его объявлениях по id
ordersRouter_BG.get('/merchant-details/:id', async (req, res) => {
	const merchantId = req.params.id;
	const axiosRequestConfig = {
		method: GET_MERCHANT_DETAILS.method,
		url: `${GET_MERCHANT_DETAILS.url}?userNo=${merchantId}`,
		data: null,
		headers: null,
	};
	await axios(axiosRequestConfig)
		.then((response) => {
			// console.log(response.data)
			return res.status(200).json({
				success: true,
				data: response.data.data,
				message: `${SHORT_NAME}: ${TEXT_CONSTANTS.USER_DETAILS_OK}`,
			});
		})
		.catch((error) => {
			res.status(400).json({
				error,
				message: `${SHORT_NAME}: ${TEXT_CONSTANTS.USER_DETAILS_ER}`,
			});
		});
});

// сохранение данных об merchant-ордере в БД по id
ordersRouter_BG.post('/save-user-orders', async (req, res) => {
	const arrTickers = await Ticker.find(); // тикеры и цены из БД
	let countOrder = 0;

	const { userId, orders, typeOrder, shortName, exchangeId } = req.body;

	// проверка наличия ордера в БД
	for (let i = 0; i < orders.length; i++) {
		if (orders[i].statusProps.value === 'Completed') {
			const result = await checkOrderInDB(
				userId,
				typeOrder,
				orders[i].orderId,
				shortName
			);

			// Если ордера нет в БД
			if (result.isUnique) {
				const params = {
					userId,
					shortName,
					exchangeId,
					arrTickers,
					// arrPayTypes,
					orderDetails: orders[i], // нормализованный ордер from frontend
				};

				const newOrder = getOrderDetailsNomalized(params);
				// если newOrder не пустой объект - сохраняем в БД
				if (Object.keys(newOrder).length !== 0) {
					await insertOrderToDB(typeOrder, newOrder);
					// console.log(
					// // `${countOrder} | Number: ${newOrder.orderId} | payMethodName: ${newOrder.payMethodName}`
					// newOrder
					// );
					++countOrder;
				}
			}
		}
	}

	// log print
	consoleProcessed(userId, shortName, orders, countOrder, typeOrder);

	return res.status(200).json({
		success: true,
		message: `${shortName}: ${countOrder} inserted`,
	});
});

// получение массива активных spot-ордеров
ordersRouter_BG.post('/spot-orders-active', async (req, res) => {
	const { userId, exchange, exchangeId, shortName } = req.body;
	const arrTickers = await Ticker.find();
	let status = 200;

	const user = await User.findOne({ _id: userId });

	const paramsAPI = {
		userId,
		prefix: `active_${SHORT_NAME}_API`,
		apiKeys: getSingleUserProperty('apiKeys', exchangeId, user.properties),
		// requestHeader,
		constants: CONSTANTS_BG,
		additionals: {},
	};

	const objReqParamsAPI = getObjectRequestParams(paramsAPI);
	const arrActiveSpots = await getSpotOrders(objParamsAPI);

	return res.status(status).json({
		success: arrActiveSpots.length === 0 ? false : true,
		message:
			arrActiveSpots.length === 0
				? `${shortName}: ${TEXT_CONSTANTS.SPOT_ORDERS_ER}`
				: `${shortName}: ${arrActiveSpots.length} ${TEXT_CONSTANTS.SPOT_ORDERS_OK}`,
		// spotOrders: [],
		spotOrders:
			arrActiveSpots.length === 0
				? []
				: getSpotOrdersNomalized(
						arrActiveSpots,
						{
							userId,
							shortName,
							exchangeId,
							flag: `active_${shortName}_API`,
						},
						arrTickers
				  ),
		tickers: arrTickers,
	});
});

// сохранение spot-ордеров в БД
ordersRouter_BG.post('/spot-orders-history', async (req, res) => {
	let message;
	let success = true;
	let status = 200;
	let countOrder = 0;

	const {
		userId,
		exchange,
		exchangeId,
		shortName,
		typeOrder,
		params,
	} = req.body;

	const user = await User.findOne({ _id: userId });

	const paramsAPI = {
		userId,
		prefix: `history_${SHORT_NAME}_API`,
		apiKeys: getSingleUserProperty('apiKeys', exchangeId, user.properties),
		// requestHeader,
		constants: CONSTANTS_BG,
		additionals: {},
	};

	const objReqParamsAPI = getObjectRequestParams(paramsAPI);
	const spotArray = await getSpotOrders(objReqParamsAPI);

	const arrTickers = await Ticker.find();
	const spotOrders = getSpotOrdersNomalized(
		spotArray,
		{
			userId,
			shortName,
			exchangeId,
			flag: `history_${shortName}_API`,
		},
		arrTickers
	);

	if (spotOrders.length !== 0) {
		// проверка наличия ордера в БД
		for (let i = 0; i < spotOrders.length; i++) {
			const result = await checkOrderInDB(
				spotOrders[i].userId,
				typeOrder,
				spotOrders[i].orderId,
				spotOrders[i].exchange
			);

			// Если ордера нет в БД вставляем
			if (result.isUnique) {
				// если newSpotOrder не пустой объект - сохраняем в БД
				if (Object.keys(spotOrders[i]).length !== 0) {
					await insertOrderToDB('SPOT', spotOrders[i]);
					// console.log(
					// 	`${countOrder} | orderId: ****${spotOrders[i].orderId.slice(
					// 		-5
					// 	)} inserted`
					// );
					++countOrder;
				}
			}
			// else console.log(`Order ${spotOrders[i].orderId} is not Unique`);
		}
		if (countOrder === 0) {
			success = false;
			message = `${shortName}: ${countOrder} | ${TEXT_CONSTANTS.SPOT_ORDERS_DB_NO}`;
		} else {
			success = true;
			message = `${shortName}: ${countOrder} | ${TEXT_CONSTANTS.SPOT_ORDERS_DB_OK}`;
		}
	} else {
		success = false;
		message = `${shortName}: ${TEXT_CONSTANTS.SPOT_ORDERS_ER}`;
	}

	// log print
	consoleProcessed(userId, shortName, spotOrders, countOrder, typeOrder);

	return res.status(status).json({
		success,
		message,
	});
});
