// 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 { inspect } from 'util';

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

export default async function handler(req, res) 
{
	await cors(req, res);
	let { emails } = req.body;

	console.log("API", "admin/remove");
	if(req.headers.cookie !== undefined)
	{
		const cookies = cookie.parse(req.headers?.cookie ? req.headers?.cookie : "");

		if(cookies.jwt !== undefined && cookies.jwt !== null)
		{
			let client_jwt_decoded = jwt.verify(cookies.jwt, process.env.JWT_SECRET_CLIENT);
			console.log("API", "admin/remove", "client_jwt_decoded", client_jwt_decoded);

			const payload = {
				acc_number: client_jwt_decoded.acc_number, 
				emails, 
			};

			const crm_jwt_token = jwt.sign(payload, process.env.JWT_SECRET_CRM, { noTimestamp: true });

			await axios.post(`${ process.env.NEXT_PUBLIC_API_HOST }/api/admin/remove/`, {
				token: crm_jwt_token, 
			})
			.then((api_response) => 
			{
				console.log("API", "auth/remove", "RESPONSE");
				console.log(inspect(api_response.data, true, null, true));

				res.status(200).send(api_response.data);
			})
			.catch((error) => 
			{
				console.error("API", "auth/remove", "error");
				console.error(error);

				res.status(403).json();
			});
		}
		else
		{
			res.status(403).json();
		}
	}
	else
	{
		res.status(403).json();
	}
}