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

export default async function handler(req, res) 
{
	await cors(req, res);

	if(req.headers.cookie !== undefined)
	{
		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(client_jwt_decoded, process.env.JWT_SECRET_CRM, { noTimestamp: true });

			const result = {
				upd: [], 
				upd_avans: [], 
				billfines: [], 
				fines: [], 
			};

			await Promise.all([ 
				new Promise((resolve) => {
					axios.get(`${ process.env.CRM_API_HOST }/lk/Contract/GetUPDListByContract`, {
						params: { ...client_jwt_decoded, contract_number: req.body.number }, 
						headers: { "Authorization": `Bearer ${ crm_jwt }`, }, 
					})
					.then((crm_response) => 
					{ 
						console.log(inspect(crm_response.data, true, null, true));
						for(let i in crm_response.data)
						{
							if(crm_response.data[i].type === "UPD")
							{
								result.upd = crm_response.data[i].upd;
							}
							if(crm_response.data[i].type === "UPD_Avans")
							{
								result.upd_avans = crm_response.data[i].upd;
							}
							if(crm_response.data[i].type === "BillFine")
							{
								result.billfines = crm_response.data[i].upd;
							}
						}
						resolve();
					})
					.catch((error) => { console.error(error); resolve(); });
				}), 
				new Promise((resolve) => {
					axios.get(`${ process.env.CRM_API_HOST }/lk/Contract/GetFineGIBDDList`, {
						params: { ...client_jwt_decoded, contract_number: req.body.number }, 
						headers: { "Authorization": `Bearer ${ crm_jwt }`, }, 
					})
					.then((crm_response) => { result.fines = crm_response.data; resolve(); })
					.catch((error) => { console.error(error); resolve(); });
				}), 
			])
			.then(() => 
			{
				res.status(200).json(result);
			});
		}
		else
		{
			res.status(403);
		}
	}
}