// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import https from 'https';
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 { get as _get, pick as _pick } from 'lodash';

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

const keepAliveAgent = new https.Agent({ keepAlive: true });

export default async function handler(req, res) 
{
	console.log("API", "questionnaire", "get");
	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({ acc_number: client_jwt_decoded.acc_number }, process.env.JWT_SECRET_CRM, { noTimestamp: true });

				const path = `${ process.env.CRM_API_HOST }/lk/Questionnaire/InfoQuestionnaire/`;

				try
				{
					const { id } = req.query;
					axios.get(path, {
						params: { name: id }, 
						headers: {
							"Authorization": `Bearer ${ crm_jwt }`, 
						} 
					})
					.then((crm_response) => 
					{
						console.log("crm_response for", path);
						console.log(inspect(crm_response.data, true, null, true));

						if(crm_response.data.licenses === null)
						{
							axios.post(`https://suggestions.dadata.ru/suggestions/api/4_1/rs/findById/party`, { query: crm_response.data.inn }, { 
								httpAgent: keepAliveAgent, 
								headers: {
									"Content-Type": "application/json",
									"Authorization": `Token ${ process.env.DADATA_API_KEY }`,
									"X-Secret": process.env.DADATA_SECRET_KEY
								}, 
							})
							.then((api_response) => 
							{
								console.log("API", "RESPONSE", "licenses");
								console.log(api_response.data.suggestions[0].data.licenses);

								const licenses_list = _get(api_response, "data.suggestions[0].data.licenses", []);
								const licenses_chunks = [];

								if(licenses_list !== null && licenses_list.length > 0)
								{
									for(let i in licenses_list)
									{
										licenses_chunks.push(
											`${ licenses_list[i].series !== null ? licenses_list[i].series+" " : "" }${ licenses_list[i].number } от ${ moment(licenses_list[i].issue_date).format("DD.MM.YYYY") }`
										);
									}
								}

								if(licenses_chunks.length > 0)
								{
									crm_response.data.licenses = licenses_chunks.join(", ");
								}

								res.status(200).json(crm_response.data);
								resolve();
							})
							.catch((error) => 
							{
								console.log("error");
								console.error(error);

								res.status(500).send();
								resolve();
							});
						}
						else
						{
							res.status(200).json(crm_response.data);
							resolve();
						}
					})
					.catch((error) => 
					{
						console.error(error);
						console.error("-".repeat(30), "error.response.data:");
						console.error(error.response.data);

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