package logic

import (
	"context"
	"errors"
	"fmt"
	"juwan-backend/app/users/rpc/internal/models/users"
	"juwan-backend/common/redisx"

	"juwan-backend/app/users/rpc/internal/svc"
	"juwan-backend/app/users/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type ResetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResetPasswordLogic {
	return &ResetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ResetPasswordLogic) ResetPassword(in *pb.ResetPasswordReq) (*pb.ResetPasswordResp, error) {
	// todo: add your logic here and delete this line
	redisKey := fmt.Sprintf(redisx.VCODE_KEY_PREFIX, in.RequestId, redisx.SCENE_RESET_PWD, in.Email)
	vcode, err := l.svcCtx.RedisCluster.Get(l.ctx, redisKey).Result()
	if err != nil {
		logx.Errorf("get reset password vcode from redis failed, err:%v.", err)
		return nil, err
	}
	if vcode != in.Vcode {
		return nil, errors.New(fmt.Sprintf("user %v reset password failed, invalid vcode.", in.Email))
	}
	// in.NewPassword is already bcrypt-hashed by the API layer
	err = l.svcCtx.UsersModelRW.Users.Update().Where(users.EmailEQ(in.Email)).
		SetPasswordHash(in.NewPassword).
		Exec(l.ctx)
	if err != nil {
		logx.Errorf("reset password failed, err:%v.", err)
		return nil, errors.New("reset password failed")
	}
	return &pb.ResetPasswordResp{}, nil
}
