package service

import (
	"github.com/zs/InsightReply/internal/model"
	"github.com/zs/InsightReply/internal/repository"
	"golang.org/x/crypto/bcrypt"
)

type UserService struct {
	repo *repository.UserRepository
}

func NewUserService(repo *repository.UserRepository) *UserService {
	return &UserService{repo: repo}
}

func (s *UserService) Register(email string, password string, identity string) (*model.User, error) {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return nil, err
	}

	user := &model.User{
		Email:         email,
		PasswordHash:  string(hashedPassword),
		IdentityLabel: identity,
	}
	err = s.repo.Create(user)
	return user, err
}

func (s *UserService) GetUser(email string) (*model.User, error) {
	return s.repo.GetByEmail(email)
}

func (s *UserService) GetUserByID(id string) (*model.User, error) {
	return s.repo.GetByID(id)
}

func (s *UserService) UpdatePreferences(id string, identity string, language string) (*model.User, error) {
	user, err := s.repo.GetByID(id)
	if err != nil {
		return nil, err
	}

	if identity != "" {
		user.IdentityLabel = identity
	}
	if language != "" {
		user.LanguagePreference = language
	}

	err = s.repo.Update(user)
	return user, err
}
