package user

import (
	"context"

	"time"

	"github.com/SamuelTariku/FortuneBet-Backend/internal/domain"
)

func (s *Service) SendResetCode(ctx context.Context, medium domain.OtpMedium, sentTo string) error {

	var err error
	// check if user exists
	switch medium {
	case domain.OtpMediumEmail:
		_, err = s.userStore.GetUserByEmail(ctx, sentTo)
	case domain.OtpMediumSms:
		_, err = s.userStore.GetUserByPhone(ctx, sentTo)
	}

	if err != nil {
		return err
	}

	return s.SendOtp(ctx, sentTo, domain.OtpReset, medium)

}

func (s *Service) ResetPassword(ctx context.Context, resetReq domain.ResetPasswordReq) error {
	var sentTo string
	if resetReq.OtpMedium == domain.OtpMediumEmail {
		sentTo = resetReq.Email
	} else {
		sentTo = resetReq.PhoneNumber
	}

	otp, err := s.otpStore.GetOtp(
		ctx, sentTo,
		domain.OtpReset, resetReq.OtpMedium)
	if err != nil {
		return err
	}
	//
	if otp.Used {
		return domain.ErrOtpAlreadyUsed
	}
	if time.Now().After(otp.ExpiresAt) {
		return domain.ErrOtpExpired
	}
	if otp.Otp != resetReq.Otp {
		return domain.ErrInvalidOtp
	}
	// hash password
	hashedPassword, err := hashPassword(resetReq.Password)
	if err != nil {
		return err
	}
	// reset pass and mark otp as used
	
	err = s.userStore.UpdatePassword(ctx, sentTo, hashedPassword, otp.ID)
	if err != nil {
		return err
	}
	return nil
}
