// 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) 
{
	await cors(req, res);
	let { acc_number } = req.body;

	console.log("API", "auth/switch");
	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", "auth/switch", "client_jwt_decoded", client_jwt_decoded);

			const { companies } = client_jwt_decoded;

			if(companies !== undefined && companies !== null)
			{
				for(let i in companies)
				{
					if(companies[i].acc_number === acc_number)
					{
						company = companies[i];
						allow = true;
						break;
					}
				}

				if(allow)
				{
					const new_client_jwt = jwt.sign({
						acc_number: acc_number, 
						is_admin: company.is_admin, 
						login: client_jwt_decoded.login, 
						companies: client_jwt_decoded.companies, 
					}, process.env.JWT_SECRET_CLIENT, { noTimestamp: true });

					res.status(200).send({
						status: "success", 
						token: new_client_jwt, 
					});
				}
				else
				{
					res.status(403).json();
				}
			}
			else
			{
				res.status(403).json();
			}
		}
		else
		{
			res.status(403).json();
		}
	}
	else
	{
		res.status(403).json();
	}
}