import fs from 'fs';
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';

export default async function handler(req, res) 
{
	console.log("\n\n", "API", "/contract/invoice/download");

	const { entity_id, code } = req.query;
	const payload = { 
		entityId: entity_id, 
		reportCodes: [ code ], 
		createDocument: false, 
		openFile: true, 
	};

	console.log({ payload });

	return new Promise(async (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({ acc_number: client_jwt_decoded.acc_number }, process.env.JWT_SECRET_CRM, { noTimestamp: true });

				try
				{
					axios.post(`${ process.env.CRM_API_HOST }/File/GetWMDoc`, payload, {
						responseType: 'arraybuffer', 
						headers: {
							"Authorization": `Bearer ${ crm_jwt }`, 
							"Content-Type": "application/json", 
						}, 
					})
					.then((crm_response) => 
					{
						res.status(200).send(crm_response.data);
						resolve();
					})
					.catch((error) => 
					{
						console.error(error);
						console.error(error.data);

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