// 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 { cors } from '../../../lib/cors';
import { inspect } from 'util';
//import formidable from 'formidable';

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

	console.log("req.query", req.query);

	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)
			{
				console.log("cookies.jwt");
				console.log(cookies.jwt);
	
				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 });

				//const path = `${ process.env.CRM_API_HOST }/lk/incident/RequestClient/UploadDocument?request_client_number=${ fields.request_client_number }`;
				const path = `${ process.env.CRM_API_HOST }/lk/incident/RequestClient/UploadDocument?request_client_number=${ req.query.request_client_number }`;
				console.log("API", "support", "request", "path", path);

				console.log("*".repeat(50));
				console.log(req.headers);
				console.log("*".repeat(50));

				try
				{
					console.log("??????", req.headers['content-type']);
					axios.post(path, req.body, 
					{
						headers: {
							"Content-Type": req.headers['content-type'], 
							//"Content-Type": "multipart/form-data", 
							"Authorization": `Bearer ${ crm_jwt }`, 
						}, 
						withCredentials: true, 
					})
					.then((crm_response) => 
					{
						console.log("crm_response for", path);
						console.log(inspect(crm_response.data, true, null, true));

						res.status(200).json(crm_response.data);
						resolve();
					})
					.catch((error) => 
					{
						console.error(error);
						console.error("-".repeat(30), "error.response.data:");
						console.error(error.response.data);

						res.status(500).json(error.response.data);
						resolve();
					});
				}
				catch(e)
				{
					console.error(e);
					res.status(500).end(e);
					resolve();
				}
			}
			else
			{
				res.status(403);
				resolve();
			}
		}
		else
		{
			res.status(403);
			resolve();
		}
	});
}

/*
export default async function handler(req, res) 
{
	console.log("API", "support", "attachment");
	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)
			{
				console.log("cookies.jwt");
				console.log(cookies.jwt);
	
				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 });

				const form = formidable({});
				form.parse(req, (err, fields, files) => 
				{
					if(err) 
					{
						console.error(err);
						res.status(500).end("");
						resolve();
					}
					else
					{
						console.log("fields", fields);
						console.log("files", files);
						console.log("API", "support", "attachment", "-".repeat(50));

						//const path = `${ process.env.CRM_API_HOST }/lk/incident/RequestClient/UploadDocument?request_client_number=${ fields.request_client_number }`;
						const path = `${ process.env.CRM_API_HOST }/lk/incident/RequestClient/UploadDocument?request_client_number=REQ2022_0000092`;
						console.log("API", "support", "request", "path", path);

						try
						{
							axios.post(path, req.body, 
							{
								headers: {
									//"Content-Type": "application/json", 
									"Content-Type": "multipart/form-data", 
									"Authorization": `Bearer ${ crm_jwt }`, 
								}, 
								withCredentials: true, 
							})
							.then((crm_response) => 
							{
								console.log("crm_response for", path);
								console.log(inspect(crm_response.data, true, null, true));

								res.status(200).json(crm_response.data);
								resolve();
							})
							.catch((error) => 
							{
								console.error(error);
								console.error("-".repeat(30), "error.response.data:");
								console.error(error.response.data);

								res.status(500).json(error.response.data);
								resolve();
							});
						}
						catch(e)
						{
							console.error(e);
							res.status(500).end(e);
							resolve();
						}
					}
				});	
			}
			else
			{
				res.status(403);
				resolve();
			}
		}
		else
		{
			res.status(403);
			resolve();
		}
	});
}

export const config = {
	api: {
		bodyParser: false
	}
}
*/
export const config = {
	api: {
		bodyParser: {
			sizeLimit: '1000mb'
		}
	}
}