package user

import (
	"context"
	"time"

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

func (s *Service) CheckPhoneEmailExist(ctx context.Context, phoneNum, email string) (bool, bool, error) { // email,phone,error
	return s.userStore.CheckPhoneEmailExist(ctx, phoneNum, email)
}
func (s *Service) SendRegisterCode(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 && err != domain.ErrUserNotFound {

		return err
	}

	// send otp based on the medium
	return s.SendOtp(ctx, sentTo, domain.OtpRegister, medium)
}
func (s *Service) RegisterUser(ctx context.Context, registerReq domain.RegisterUserReq) (domain.User, error) { // normal
	// get otp

	var sentTo string
	if registerReq.OtpMedium == domain.OtpMediumEmail {
		sentTo = registerReq.Email
	} else {
		sentTo = registerReq.PhoneNumber
	}
	//
	otp, err := s.otpStore.GetOtp(
		ctx, sentTo,
		domain.OtpRegister, registerReq.OtpMedium)
	if err != nil {
		return domain.User{}, err
	}
	// verify otp
	if otp.Used {
		return domain.User{}, domain.ErrOtpAlreadyUsed
	}
	if time.Now().After(otp.ExpiresAt) {
		return domain.User{}, domain.ErrOtpExpired
	}
	if otp.Otp != registerReq.Otp {
		return domain.User{}, domain.ErrInvalidOtp
	}

	hashedPassword, err := hashPassword(registerReq.Password)
	if err != nil {
		return domain.User{}, err
	}
	userR := domain.User{
		FirstName:     registerReq.FirstName,
		LastName:      registerReq.LastName,
		Email:         registerReq.Email,
		PhoneNumber:   registerReq.PhoneNumber,
		Password:      hashedPassword,
		Role:          domain.RoleCustomer,
		EmailVerified: registerReq.OtpMedium == domain.OtpMediumEmail,
		PhoneVerified: registerReq.OtpMedium == domain.OtpMediumSms,
	}
	// create the user and mark otp as used
	user, err := s.userStore.CreateUser(ctx, userR, otp.ID, false)
	if err != nil {
		return domain.User{}, err
	}
	return user, nil
}
