// 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';

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

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 redis.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;
					/*
					const appeals = [
						{ 
							number: "CAS-02991-J2M9B8", 
							created_date: "2021-09-06", 
							subject: "Вопросы по пени и штрафам", 
							owner: "Анастасия Ломакина", 
							status: "cancelled", 
							answer: "", 
							contracts: "No2021_1889, No2021_2453, No2021_2465, No2021_2857", 
							documents: [ 
								{ 
									doc_name: "Письмо от ЛП", 
									doc_url: "24bfe404-9905-4b69-8898-09a7229a8fc1", 
									doc_extension: "pdf", 
								}, 
								{ 
									doc_name: "Пояснения СБ", 
									doc_url: "24bfe404-9905-4b69-8898-09a7229a8fc1", 
									doc_extension: "pdf", 
								}, 
							], 
						}, 
						{ 
							number: "CAS-01779-S2Q3Q6", 
							created_date: "2021-06-22", 
							subject: "Изменение графика", 
							owner: "Анастасия Ломакина", 
							status: "active", 
							answer: "", 
							contracts: "No2021_1889, No2021_1891, No2021_1914, No2021_2453, No2021_3023, No2021_7349, No2021_9969, No2021_125 95", 
							documents: [ 
								{ 
									doc_name: "Запрос на выезд за границу", 
									doc_url: "4291c8b0-2aff-47a1-b246-fc8e5e196c24", 
									doc_extension: "pdf", 
								}, 
								{ 
									doc_name: "согласование УЭБ", 
									doc_url: "4291c8b0-2aff-47a1-b246-fc8e5e196c24", 
									doc_extension: "pdf", 
								}, 
							], 
						}, 
						{ 
							number: "CAS-01691-L2Z7H2", 
							created_date: "2021-06-08", 
							subject: "Выдача документов по сделке", 
							owner: "Анастасия Ломакина", 
							status: "closed", 
							answer: "", 
							contracts: "No2021_1889, No2021_3023, No2021_7349, No2021_9969, No2021_12595", 
							documents: [ 
								{ 
									doc_name: "Доп. соглашение по КАСКО", 
									doc_url: "7e11a7b0-0246-44ea-8f92-65698b79ea36", 
									doc_extension: "pdf", 
								}, 
								{ 
									doc_name: "Запрос на выезд за границу", 
									doc_url: "7e11a7b0-0246-44ea-8f92-65698b79ea36", 
									doc_extension: "pdf", 
								}, 
								{ 
									doc_name: "письмо о назначении платежей", 
									doc_url: "7e11a7b0-0246-44ea-8f92-65698b79ea36", 
									doc_extension: "pdf", 
								}, 
								{ 
									doc_name: "ПП по платежу за июнь", 
									doc_url: "7e11a7b0-0246-44ea-8f92-65698b79ea36", 
									doc_extension: "pdf", 
								}, 
								{ 
									doc_name: "ПП по расширению страхового покрытия", 
									doc_url: "7e11a7b0-0246-44ea-8f92-65698b79ea36", 
									doc_extension: "pdf", 
								}
							], 
						}
					];
					*/

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