// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import axios from 'axios';
import { Cookies } from 'react-cookie';
import cookie from 'cookie';
import moment from 'moment';
import jwt from 'jsonwebtoken';
import { inspect } from 'util';
import { captureException, getCurrentScope } from '@sentry/nextjs';

import { cors } from '../cors';

export default async function CRMRequest(req, res, path, method, data, log = false) 
{
	await cors(req, res);

	if(req.headers.cookie !== undefined)
	{
		console.debug("CRMRequest", "REQUEST", path);
		const cookies = cookie.parse(req.headers?.cookie ? req.headers?.cookie : "");

		if(cookies.jwt !== undefined && cookies.jwt !== null)
		{
			var client_jwt_decoded = jwt.verify(cookies.jwt, process.env.JWT_SECRET_CLIENT);
			var crm_jwt = jwt.sign({ acc_number: client_jwt_decoded.acc_number }, process.env.JWT_SECRET_CRM, { noTimestamp: true });

			if(log)
			{
				console.log("client_jwt_decoded", client_jwt_decoded);
				console.log("crm_jwt", crm_jwt);
				console.log("path", path);
			}

			try
			{
				axios.request({
					url: path, 
					method, 
					headers: {
						"Authorization": `Bearer ${ crm_jwt }`, 
						"Content-Type": "application/json"
					}, 
					data, 
				})
				.then((crm_response) => 
				{
					if(log)
					{
						console.log("crm_response for", path);
						console.log("payload", payload);
						console.log(inspect(crm_response.data, true, null, true));
					}

					res.status(200).json(crm_response.data);
				})
				.catch((error) => 
				{
					const scope = getCurrentScope();
					scope.setExtras({
						path, data
					});

					scope.setTag("account", `${ client_jwt_decoded.acc_number }`);
					scope.setTag("offstage", `${ client_jwt_decoded.observer ? true : false }`);
					scope.setUser({ email: client_jwt_decoded.login.indexOf("@") > -1 ? client_jwt_decoded.login : null, phone: client_jwt_decoded.login.indexOf("@") < 0 ? client_jwt_decoded.login : null });
					captureException(error);

					if(log)
					{
						console.error(error);
						console.error("-".repeat(30), "error.response.data:");
						console.error(error.response.data);
					}

					res.status(500).json(error.response.data);
				});
			}
			catch(e)
			{
				console.error(e);
				res.status(500).send(e);
			}
		}
		else
		{
			res.status(403);
		}
	}
}