// 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, limits: { fileSize: 1024 * 1024 * 300 } });

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

				upload.single("file")(req, {}, async (err) => 
				{
					const { file, } = req;
					const { deal_id, document_id, document_name, group, type, index, lastModified, } = req.query;

					console.log({ deal_id, document_id, document_name, group, type, index, lastModified, });

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

					const file_payload = { 
						name: Buffer.from(file.originalname, 'latin1').toString('utf8'), 
						filename: local_filename, 
						document_id: document_id, 
						group, 
						index, 
						type, 
						uploaded: true, 
						lastModified, 
					};

					try
					{
						fs.writeFileSync(`${ __dirname }/../../../../../../uploads/deals/${ local_filename }`, file.buffer);
						console.log("multer.upload.single file");
						console.log({ file_payload });

						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)
							{
								uploaded[ group ].files.push(file_payload);
							}
							else
							{
								uploaded[ group ] = {
									id: document_id, 
									name: document_name, 
									files: [ file_payload ], 
								}
							}
						}

						deals[ deal_id ] = { uploaded };

						await RedisClient.set(key, JSON.stringify(deals));

						res.status(200).json(file_payload);
						resolve();
					}
					catch(upload_single_error)
					{
						console.error("upload_single_error");
						console.error(upload_single_error);
						res.status(500).send();
						resolve();
					}
				});
			}
			else
			{
				res.status(403).send();
				resolve();
			}
		}
	});
}

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