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

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

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

	const key = md5(`phone_change_sms_code_${ phone }`);
	await RedisClient.set(key, JSON.stringify({
		email, phone, code
	}), '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();
	});
}