/*
2.7.4 - Метод получения списка документов для рассмотрения Лизинговой сделке в CRM
GET /lk/ConsiderationOpportunity/document
*/

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 RedisClient from '../../../lib/RedisClient';

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

	await cors(req, res);
	const { deal_id } = req.body;

	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
				{
					axios.get(`${ process.env.CRM_API_HOST }/lk/ConsiderationOpportunity/document`, {
						params: { opp_number: deal_id }, 
						headers: {
							"Authorization": `Bearer ${ crm_jwt }`, 
						} 
					})
					.then(async (crm_response) => 
					{
						const documents = crm_response.data;

						const key = `deals_${ client_jwt_decoded.acc_number }`;
						var deals = await RedisClient.get(key);

						console.log({ key })

						var files = {};
						var uploaded = {};
						if(deals !== null)
						{
							deals = JSON.parse(deals);

							if(deals[ deal_id ] !== undefined)
							{
								files = deals[ deal_id ].files;
								uploaded = deals[ deal_id ].uploaded;
							}
						}

						res.status(200).send({ documents, files, uploaded, });
						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();
		}
	});
}