package service

import (
	"context"
	"fmt"
	"time"
	"youngee_b_api/consts"
	"youngee_b_api/db"
	"youngee_b_api/redis"
)

var Register *register

type register struct {
	sessionTTL time.Duration
}

func (r *register) AuthRegister(ctx context.Context, phone string, code string) (string, error) {
	user, err := db.GetUserByPhone(ctx, phone)
	if err != nil {
		return "", err
	} else if user != nil {
		return "手机号已存在", nil
	} else {
		vcode, err := r.getSession(ctx, phone)
		if err != nil {
			return "", err
		} else {
			if *vcode != code {
				return "验证码有误", nil
			} else {
				return "", nil
			}
		}
	}
}

func (r *register) getSession(ctx context.Context, phone string) (*string, error) {
	value, err := redis.Get(ctx, r.getRedisKey(phone))
	if err != nil {
		if err == consts.RedisNil {
			return nil, fmt.Errorf("not found in redis,phone:%+v", phone)
		}
		return nil, err
	}
	return &value, nil
}

func (r *register) getRedisKey(key string) string {
	return fmt.Sprintf("%s%s", consts.SessionRedisPrefix, key)
}
