// 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 { name, phone, rating, comment } = req.body;

	console.log("API", "feedbacks/add");
	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);

			await axios.post(`${ process.env.NEXT_PUBLIC_API_HOST }/api/feedbacks/add/`, {
				token: jwt.sign({ "acc_number": client_jwt_decoded.acc_number, "login": client_jwt_decoded.login }, process.env.JWT_SECRET_CRM, { noTimestamp: true }), 
				name, phone, rating, comment, 
			})
			.then((api_response) => 
			{
				console.log("API", "feedbacks/add", "RESPONSE");
				console.log(inspect(api_response.data, true, null, true));

				res.status(200).send(api_response.data);
			})
			.catch((error) => 
			{
				console.error("API", "feedbacks/add", "error");
				console.error(error);
	
				res.status(403).json();
			});
		}
		else
		{
			res.status(403).json();
		}
	}
	else
	{
		res.status(403).json();
	}
}