
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);
	let { phone, code } = req.body;
	let token = "";

	phone = phone.replace(/[^0-9.]/g, '');

	const key = md5(`phone_change_sms_code_${ phone }`);
	let existed_data = await redis.get(key);

	if(existed_data !== null)
	{
		const existed_data_json = JSON.parse(existed_data);

		if(existed_data_json.code === code)
		{
			console.log("existed_data_json");
			console.log(existed_data_json);
			console.log("*".repeat(50));

			const cookies = cookie.parse(req.headers?.cookie ? req.headers?.cookie : "");
			const response = await new Promise((resolve, reject) => 
			{
				axios.post(`${ process.env.NEXT_PUBLIC_API_HOST }/api/account/change/phone/`, {
					email: existed_data_json.email, 
					phone, 
				}, {
					headers: {
						"Authorization": `Bearer ${ cookies.jwt }`, 
					}, 
				})
				.then((api_response) => 
				{
					console.log("RESPONSE FROM API");
					console.log(api_response.data);

					resolve({ status: "success" });
				})
				.catch((error) => 
				{
					console.log("RESPONSE FROM API");
					console.error("error");
					console.error(error);

					resolve({ status: "error" });
				});
			});

			if(response.status === "success")
			{
				res.status(200).json({ status: "success", });
			}
			else
			{
				res.status(403).json();
			}	
		}
		else
		{
			res.status(403).json();
		}
	}
	else
	{
		res.status(403).json();
	}
}