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

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

	console.log("API", "file", "contract", "graphic");
	console.log(req.query);
	console.log("-".repeat(50));

	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
			{
				axios.get(`${ process.env.CRM_API_HOST }/lk/add-contract/GetPreCalculationGraphPrintForm`, {
					params: { addcontract_number: req.query.calculation }, 
					headers: {
						"Authorization": `Bearer ${ crm_jwt }`, 
					} 
				})
				.then((crm_response) => 
				{
					console.log("API", "/file/contract/graphic", "crm_response.data");

					res.setHeader("filename", Buffer.from(crm_response.data.key).toString('base64'));
					res.status(200).send(Buffer.from(crm_response.data.value, 'base64'));
				})
				.catch((error) => 
				{
					console.error(error);
					res.status(500);
				});
			}
			catch(e)
			{
				console.error(e);
				res.status(500);
			}
		}
		else
		{
			res.status(403);
		}
	}
}