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

export default async function handler(req, res) 
{
	console.log("API\n\n\n\n\n\n\n");
	console.log("API", "file", "image");

	await cors(req, res);

	if(req.headers.cookie !== undefined)
	{
		console.log("api 1");
		const cookies = cookie.parse(req.headers?.cookie ? req.headers?.cookie : "");

		if(cookies.jwt !== undefined && cookies.jwt !== null)
		{
			console.log("api 2");
			var client_jwt_decoded = jwt.verify(cookies.jwt, process.env.JWT_SECRET_CLIENT);
			var crm_jwt = jwt.sign(client_jwt_decoded, process.env.JWT_SECRET_CRM, { noTimestamp: true });

			console.log("api 3");
			console.log("API", "file", "image", "/file/GetImage", "req.query.id", req.query.id);

			await axios.get(`${ process.env.CRM_API_HOST }/file/GetImage`, {
				params: { id: req.query.id }, 
				responseType: 'arraybuffer',
				headers: {
					"Authorization": `Bearer ${ crm_jwt }`, 
				} 
			})
			.then((crm_response) => 
			{
				try
				{
					console.log("crm_response.data");
					console.log(crm_response.data);
					const base64image = `data:${ crm_response['headers']['content-type'] };base64,${ Buffer.from(crm_response.data, 'binary').toString('base64') }`;

					console.log("base64image");
					console.log(base64image);

					res.status(200).send(base64image);
				}
				catch(e)
				{
					console.error(e);
					res.status(500);
				}	
			})
			.catch((error) => 
			{
				console.error(error);
				res.status(500);
			});
		}
		else
		{
			res.status(403);
		}
	}
	else
	{
		console.log("WTF?!?!?!!?");
	}
}