package services

import (
	"errors"
	"learnsteam/learsteam-quiz-api/internal/models"
	"learnsteam/learsteam-quiz-api/internal/repositories"

	"github.com/google/uuid"
	"golang.org/x/crypto/bcrypt"
)

type authService struct {
	userRepository  repositories.UserRepository
	tokenRepository repositories.TokenRepository
}

type AuthService interface {
	Register(*models.RegisterRequest) (*models.User, error)
	Login(*models.LoginRequest) (*models.User, error)
}

func NewAuthService(userRepository repositories.UserRepository, tokenRepository repositories.TokenRepository) AuthService {
	return &authService{
		userRepository:  userRepository,
		tokenRepository: tokenRepository,
	}
}

func (s *authService) Register(request *models.RegisterRequest) (*models.User, error) {
	hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), 10)
	if err != nil {
		return nil, errors.New("fail to hash password")
	}

	// Create the user
	newUser := models.User{
		ID:       uuid.NewString(),
		Username: request.Username,
		Name:     request.Name,
		Score:    0,
		Password: string(hash),
	}

	user, err := s.userRepository.Create(&newUser)
	if err != nil {
		return nil, errors.New("fail to create user")
	}

	return user, err
}

func (s *authService) Login(request *models.LoginRequest) (*models.User, error) {
	user, err := s.userRepository.FindByUsername(request.Username)
	if err != nil || user == nil {
		return nil, errors.New("invalid user or password")
	}

	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(request.Password))
	if err != nil {
		return nil, errors.New("invalid user or password")
	}
	return user, nil
}
