// 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 Redis from 'ioredis';
import md5 from 'md5';
import { inspect } from 'util';
import multer from 'multer';

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

const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

export default async function handler(req, res) 
{
	console.log("\n\n", "API", "DEALS", "FILE", "remove");
	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);

				const { deal_id, group, index } = req.query;
				const local_filename = `${ client_jwt_decoded.acc_number }_${ deal_id }_${ group }_${ index }`;

				try
				{
					console.log("local_filename", local_filename);
					const filename = `${ __dirname }/../../../../../../uploads/deals/${ local_filename }`;

					if (fs.existsSync(filename))
					{
						fs.unlinkSync(filename);
					}

					const key = `deals_${ client_jwt_decoded.acc_number }`;
					var deals = await RedisClient.get(key);

					var uploaded = {};
					var files = {};
					if(deals !== null)
					{
						deals = JSON.parse(deals);

						if(deals[ deal_id ] !== undefined)
						{
							//files = deals[ deal_id ].files;
							uploaded = deals[ deal_id ].uploaded;
						}
					}
					else
					{
						deals = {};
					}

					if(uploaded !== undefined)
					{
						if(uploaded[ group ] !== undefined)
						{
							if(uploaded[ group ].files !== undefined)
							{
								console.log({ files: uploaded[ group ].files });

								uploaded[ group ].files.splice(index, 1);
							}
						}
					}

					deals[ deal_id ] = { uploaded };

					await RedisClient.set(key, JSON.stringify(deals));
//					}
//					else
//					{
//						console.error("NOT exists filename", filename);
//					}

					res.status(200).send();
					resolve();
				}
				catch(remove_single_error)
				{
					console.error("remove_single_error");
					console.error(remove_single_error);

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

export const config = {
	api: {
		bodyParser: false
	}
}