// 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';

const validateEmail = (email) => {
	return email.match(
		/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
	);
};

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

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

		if(cookies.jwt !== undefined && cookies.jwt !== null)
		{
			let allow = false;
			let company = {};
			let client_jwt_decoded = jwt.verify(cookies.jwt, process.env.JWT_SECRET_CLIENT);

			console.log("API", "admin/invite", "client_jwt_decoded", client_jwt_decoded);

			const admin_companies = client_jwt_decoded.companies;
			const allowed_companies = [];

			if(validateEmail(email))
			{
				if(admin_companies !== undefined && admin_companies !== null)
				{
					if(companies !== undefined && companies !== null)
					{
						for(let c in companies)
						{
							for(let ac in admin_companies)
							{
								if(admin_companies[ac].acc_number === companies[c])
								{
									allowed_companies.push(companies[c]);
								}
							}
						}

						if(allowed_companies.length > 0)
						{
							const payload = { name, email, companies, };
							console.log("payload");
							console.log(payload);

							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/invite/`, {
								token: crm_jwt_token, 
							})
							.then((api_response) => 
							{
								console.log("API", "auth/invite", "RESPONSE");
								console.log(inspect(api_response.data, true, null, true));

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

								res.status(403).json();
							});	
						}
						else
						{
							res.status(403).json();
						}
					}
					else
					{
						res.status(403).json();
					}
				}
				else
				{
					res.status(403).json();
				}
			}
			else
			{
				res.status(400).json({ errors: [ "email" ]});
			}
		}
		else
		{
			res.status(403).json();
		}
	}
	else
	{
		res.status(403).json();
	}
}