// 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 Redis from 'ioredis';
import md5 from 'md5';

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

const redis = new Redis(process.env.REDIS_URL);

export default async function handler(req, res) 
{
	await cors(req, res);

	let { appeals } = req.body;

	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(client_jwt_decoded, process.env.JWT_SECRET_CRM, { noTimestamp: true });

			console.log("client_jwt_decoded");
			console.log(client_jwt_decoded);

			try
			{
				for(let i in appeals)
				{
					const key = `${ client_jwt_decoded.acc_number }_appeal_${ appeals[i].number }_${ appeals[i].status }`;
					console.log("API", "support", "read", "key", key);

					await redis.set(key, appeals[i].status);
				}
			}
			catch(exception)
			{
				console.error("EXCEPTION", "API", "support", "read");
				console.error(exception);
			}
		}
	}

	res.status(200).json({
		status: "success", 
	});
}