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 nodemailer from "nodemailer";

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

const transporter = nodemailer.createTransport({ 
	host: process.env.EMAIL_HOSTNAME, 
	port: 465, 
	secure: true, 
	auth: { 
		user: process.env.EMAIL_USERNAME, 
		pass: process.env.EMAIL_PASSWORD, 
	}, 
});

console.log({ host: process.env.EMAIL_HOSTNAME, user: process.env.EMAIL_USERNAME, pass: process.env.EMAIL_PASSWORD });

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

				upload.array("files", 10)(req, {}, (err) => 
				{
					const { contract_number, deal_id,  } = req.body;
					const { files } = req;

					const attachments = [];
					for(let i in files)
					{
						attachments.push({
							filename: Buffer.from(files[i].originalname, 'latin1').toString('utf8'), 
							content: files[i].buffer, 
						});
					}

					axios.get(`${ process.env.CRM_API_HOST }/lk/Account/GetCompanyInfo/`, {
						params: {
							acc_number: client_jwt_decoded.acc_number, 
						}, 
						headers: {
							"Authorization": `Bearer ${ crm_jwt }`, 
						}
					})
					.then(async (crm_response) => 
					{
						console.log({ crm_response: crm_response.data });
						const { manager_email } = crm_response.data;

						if(manager_email !== undefined && manager_email !== null && manager_email !== "")
						{
							const mail_result = await transporter.sendMail({
								from: process.env.EMAIL_USERNAME, 
								to: manager_email, 
								subject: `Скан договора №${ contract_number } для сделки №${ deal_id }`, 
								text: `Клиентом загружен скан договора №${ contract_number } для сделки №${ deal_id }`, 
								attachments, 
							});
							console.log({ mail_result });
						}

						res.status(200).send();
						resolve();
					})
					.catch((crm_error) => 
					{
						console.error("\n\n", "API", "SIGN", "/document/upload");
						console.error(crm_error);

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

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