// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import fs from 'fs';
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 md5 from 'md5';

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

export default async function handler(req, res) 
{
	console.log("API", "questionnaire", "save");
	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({ acc_number: client_jwt_decoded.acc_number }, process.env.JWT_SECRET_CRM, { noTimestamp: true });

				console.log(req.body);
				const { questionnaire } = req.body;
				//console.log("file", { file });

				const key = md5(`questionnaire_${ client_jwt_decoded.acc_number }`);
				await RedisClient.set(key, JSON.stringify(questionnaire));

				res.status(200).send();
				resolve();
			}
			else
			{
				res.status(403).send();
				resolve();
			}
		}
	});
}