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

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

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

	await cors(req, res);

	const { quote_number, } = req.query;

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

				const payload = { 
					quote_number, 
					acc_number: client_jwt_decoded.acc_number, 
				};

				console.log({ payload });

				try
				{
					axios.get(`${ process.env.CRM_API_HOST }/lk/ConsiderationOpportunity/quote/offerprintform`, {
						params: payload, 
						responseType: 'arraybuffer', 
						headers: {
							"Authorization": `Bearer ${ crm_jwt }`, 
							"Content-Type": "application/json", 
						}, 
					})
					.then((crm_response) => 
					{
						console.log("API", "DEALS", "/offer/download", "RESPONSE");
						res.status(200).send(crm_response.data);
						resolve();
					})
					.catch((error) => 
					{
						console.error("API", "DEALS", "/offer/download", "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();
		}
	});
}