package service

import (
	"hamster-tycoon/storage/dao"
	"hamster-tycoon/storage/model"
	"hamster-tycoon/utils"
)

type UserService struct {
	serviceContext
}

func NewUserService(database dao.Database) *UserService {
	return &UserService{serviceContext{db: database}}
}

func (us *UserService) GetUserFromGoogleID(googleUserID string) (*model.User, error) {
	user, err := us.db.GetUsersByGoogleID(googleUserID)
	if err != nil {
		if castedError, ok := err.(*dao.Error); ok {
			switch castedError.Type {
			case dao.ErrTypeNotFound:
				return nil, &model.ErrNotFound
			default:
				return nil, &model.ErrInternalServer
			}
		}
		return nil, &model.ErrInternalServer
	}
	return user, nil
}

func (us *UserService) CreateUserFromGoogleToken(id string, email string) (*model.User, error) {
	randNick := utils.String(20)
	user := &model.User{UserEditable: model.UserEditable{Nickname: "player-" + randNick}, GoogleID: id}
	err := us.db.CreateUser(user)
	return user, err

}
