// 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 SmsCenter = require('../../../../lib/SmsCenter');

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

export default async function handler(req, res) 
{
	await cors(req, res);
	let { phone } = req.body;
	phone = phone.replace(/[^0-9.]/g, '');

	const response = await new Promise((resolve, reject) => 
	{
		console.log("POST", `${ process.env.NEXT_PUBLIC_API_HOST }/api/account/auth/phone/`);
		axios.post(`${ process.env.NEXT_PUBLIC_API_HOST }/api/account/auth/phone/`, {
			phone: phone, 
		})
		.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")
	{
		let code = ``;
		for(let i = 0; i < 6; i++) { code = `${code}${Math.floor(Math.random()*10)}`; }

		response.code = code;

		const key = md5(`sms_code_${ phone }`);
		await redis.set(key, JSON.stringify(response), 'EX', 300);

		const smsResult = await SmsCenter.send(phone, code)
		.then(() => 
		{
			res.status(200).json({
				status: "success", 
			});
		})
		.catch((error) => 
		{
			console.error("SmsCenter.send", "catch");
			res.status(404).json();
		});	
	}
	else
	{
		res.status(404).json();
	}
}