package repository

import (
	"context"

	"backend/pkg/member/domain"
	"backend/pkg/member/domain/repository"

	"github.com/zeromicro/go-zero/core/stores/redis"
)

type VerifyCodeRepository struct {
	redis *redis.Redis
}

func NewVerifyCodeRepository(r *redis.Redis) repository.VerifyCodeRepository {
	return &VerifyCodeRepository{
		redis: r,
	}
}

func (repo *VerifyCodeRepository) IsVerifyCodeExist(ctx context.Context, loginID, checkType string) (string, error) {
	rk := domain.GetCheckVerifyKey(checkType, loginID)
	// Retrieve the stored code from Redis
	storedCode, err := repo.redis.GetCtx(ctx, rk)
	if err != nil {
		return "", err
	}

	// Check if the code exists in Redis
	if storedCode == "" {
		return "", nil
	}

	return storedCode, nil
}

func (repo *VerifyCodeRepository) SetVerifyCode(ctx context.Context, loginID, checkType, code string) error {
	rk := domain.GetCheckVerifyKey(checkType, loginID)
	err := repo.redis.SetexCtx(ctx, rk, code, 600)
	if err != nil {
		return err
	}

	return nil
}

func (repo *VerifyCodeRepository) DelVerifyCode(ctx context.Context, loginID, checkType string) error {
	rk := domain.GetCheckVerifyKey(checkType, loginID)
	_, err := repo.redis.DelCtx(ctx, rk)
	if err != nil {
		return err
	}

	return nil
}
