// 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 { cors } from '../cors';
import { inspect } from 'util';

export default async function CRMRequestGet(req, res, path, params) 
{
	await cors(req, res);

	if(req.headers.cookie !== undefined)
	{
		const cookies = cookie.parse(req.headers?.cookie ? req.headers?.cookie : "");

		console.log("-".repeat(50));
		console.log("CRMRequestGet", "req.body");
		console.log(req.body);

		if(cookies.jwt !== undefined && cookies.jwt !== null)
		{
			console.log("cookies.jwt");
			console.log(cookies.jwt);

			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 });

			console.log("client_jwt_decoded", client_jwt_decoded);
			console.log("crm_jwt", crm_jwt);

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

			try
			{
				await axios.get(path, {
					params: { ...{ acc_number: client_jwt_decoded.acc_number }, ...params }, 
					headers: {
						"Authorization": `Bearer ${ crm_jwt }`, 
					}, 
					withCredentials: true, 
				})
				.then((crm_response) => 
				{
					console.log("crm_response for", path);
					console.log(inspect(crm_response.data, true, null, true));

					res.status(200).json(crm_response.data);
				})
				.catch((error) => 
				{
					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);
		}
	}
}