package repository

import (
	"fmt"
	"log"
	"strconv"
	"time"

	"github.com/go-redis/redis"
)

type OTPActions interface {
	StoreOTP(mobno string)
	VerifyOTP(mobno string, role int, otp int) (bool, error)
}

type OTPRepository struct {
	redisClient *redis.Client
}

func OTPRepositoryInit(redisDb *redis.Client) *OTPRepository {
	return &OTPRepository{
		redisClient: redisDb,
	}
}

func (otpRepo *OTPRepository) StoreOTP(mobno string, otp int) {
	//fmt.Println("SET Error")
	err := otpRepo.redisClient.Set(mobno, otp, 15*time.Minute).Err()
	if err != nil {
		log.Println("OTPRepository: StoreOTP: RedisSet: input: ",mobno, " Error: ", err.Error())
		fmt.Println("SET", err)
	} else {
		val, err := otpRepo.redisClient.Get(mobno).Result()
		if err != nil {
			log.Println("OTPRepository: StoreOTP: RedisGet: input: ",mobno, " Error: ", err.Error())
			fmt.Println(err)
			fmt.Println("GET", err)
		} else {
			fmt.Println(val)
		}
	}

}

func (otpRepo *OTPRepository) VerifyOTP(mobno string, role int, otp int64) (bool, error) {
	val, err := otpRepo.redisClient.Get(mobno).Result()
	if err != nil {
		//fmt.Println(err)
		log.Println("OTPRepository: VerifyOTP: RedisGet: Input: ", mobno, " Error ", err.Error())
		return false, err

	} else {
		fmt.Println("Actual ", val)
		otpSer, _ := strconv.ParseInt(val, 10, 64)
		if otpSer == otp {
			return true, nil
		} else {
			return false, nil
		}
	}
}
