// 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 { inspect } from 'util';

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

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

//	console.log("API", "support", "appeals", req.headers);

	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);

			const read = await RedisClient.keys(`${ client_jwt_decoded.acc_number }_appeal_*`);
//			console.log("API", "support", "appeals", "read", read);

			try
			{
				await axios.get(`${ process.env.CRM_API_HOST }/lk/Account/GetIncidents/`, {
					params: client_jwt_decoded, 
					headers: {
						"Authorization": `Bearer ${ crm_jwt }`, 
					}
				})
				.then((crm_response) => 
				{
					let unread = 0;
//					console.log("API", "support", "appeals", "response", inspect(crm_response.data, true, null, true));

					const appeals = crm_response.data;

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

						if(read.indexOf(key) > -1)
						{
							appeals[i].read = true;
						}
						else
						{
							unread++;
						}
					}
					//res.status(200).json(crm_response.data);
					res.status(200).json({ 
						new: unread, 
						appeals
					});
				})
				.catch((error) => 
				{
					console.error(error);
					res.status(500).send();
				});
			}
			catch(e)
			{
				console.error(e);
				res.status(500).send();
			}
		}
		else
		{
			res.status(403).send();
		}
	}
	else
	{
		res.status(403).send();
	}
}