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

const storage = multer.memoryStorage();
const upload = multer({ storage: storage, limits: { fileSize: 1024 * 1024 * 300 } });

export default async function handler(req, res) 
{
	console.log("API", "questionnaire", "get");
	await cors(req, res);

	return new Promise((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);
				var crm_jwt = jwt.sign({ acc_number: client_jwt_decoded.acc_number }, process.env.JWT_SECRET_CRM, { noTimestamp: true });

				upload.single("file")(req, {}, async (err) => 
				{
					const { file, body } = req;

					const id = md5(`${ file.buffer }`);
					const local_filename = `${ client_jwt_decoded.acc_number }_${ id }`;

					const file_payload = { 
						id: id, 
						name: Buffer.from(file.originalname, 'latin1').toString('utf8'), 
						filename: local_filename, 
					};

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

						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
	}
}