// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
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) 
{
	console.log("API", "company");
	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)
			{
				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/Account/GetCompanyInfo/`, {
						params: {
							acc_number: client_jwt_decoded.acc_number, 
						}, 
						headers: {
							"Authorization": `Bearer ${ crm_jwt }`, 
						}
					})
					.then((crm_response) => 
					{
						console.log("/Account/GetCompanyInfo/", "RESPONSE", { data: crm_response.data });
						res.status(200).json({ ...crm_response.data, ...{ active: client_jwt_decoded.acc_number } });
					})
					.catch((error) => 
					{
						console.error(error);
						res.status(500).send();
					});
				}
				catch(e)
				{
					console.error(e);
					res.status(500).send();
				}
			}
			else
			{
				res.status(403).send();
			}
		}
	});
}