// 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 { cors } from '../../../lib/cors';

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

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

	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)
			{
				if(jwt.verify(cookies.jwt, process.env.JWT_SECRET_CLIENT))
				{
					try
					{
						const { query, } = req.body;

						axios.post(`https://suggestions.dadata.ru/suggestions/api/4_1/rs/findById/party`, { query }, { 
							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("RESPONSE");
							//console.log(api_response.data);

							res.status(200).send(api_response.data);
							resolve();
						})
						.catch((error) => 
						{
							console.log("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();
			}
		}
	});
}