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

	return new Promise((resolve) => 
	{
		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 });

				try
				{
					const payload = { ...client_jwt_decoded, contract_number: req.query.contract, dateBegin: req.query.date_from, dateEnd: req.query.date_to, };
					console.log(inspect(payload, true, null, true));

					axios.get(`${ process.env.CRM_API_HOST }/lk/Contract/GetAktBU/`, {
						params: payload, 
						responseType: 'arraybuffer', 
						headers: {
							"Authorization": `Bearer ${ crm_jwt }`, 
						} 
					})
					.then((crm_response) => 
					{
						res.status(200).send(crm_response.data);
						resolve();
					})
					.catch((error) => 
					{
						console.error(error);
						res.status(500).send();
						resolve();
					});
				}
				catch(e)
				{
					console.error(e);
					res.status(500).send();
					resolve();
				}
			}
			else
			{
				res.status(403).send();
				resolve();
			}
		}
		else
		{
			res.status(403).send();
			resolve();
		}
	});
}