// 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 Redis from 'ioredis';
import md5 from 'md5';

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

const redis = new Redis(process.env.REDIS_URL);

export default async function handler(req, res) 
{
	await cors(req, res);
	const { email } = req.body;

	let code = ``;
	for(let i = 0; i < 10; i++) { code = `${code}${Math.floor(Math.random()*10)}`; }

	const response = await new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_API_HOST }/api/account/recovery/email/`, {
			email, 
			code, 
		})
		.then((api_response) => 
		{
			console.log("RESPONSE");
			console.log(api_response.data);

			resolve(api_response.data);
		})
		.catch((error) => 
		{
			console.log("error");
			console.error(error);

			reject();
		});
	});

	console.log("CHECK response");
	console.log(response);
	console.log("-".repeat(50));

	if(response.status === "success")
	{
		const key = md5(`email_code_${ email }`);
		await redis.set(key, JSON.stringify({ code }), 'EX', 300);

		res.status(200).json({
			status: "success", 
		});
	}
	else
	{
		res.status(404).json();
	}
}