package service

import (
	"github.com/rs/zerolog"
	"go-humas-be/app/module/user_levels/mapper"
	"go-humas-be/app/module/user_levels/repository"
	"go-humas-be/app/module/user_levels/request"
	"go-humas-be/app/module/user_levels/response"
	"go-humas-be/utils/paginator"
)

// UserLevelsService
type userLevelsService struct {
	Repo repository.UserLevelsRepository
	Log  zerolog.Logger
}

// UserLevelsService define interface of IUserLevelsService
type UserLevelsService interface {
	All(req request.UserLevelsQueryRequest) (userLevels []*response.UserLevelsResponse, paging paginator.Pagination, err error)
	Show(id uint) (userLevels *response.UserLevelsResponse, err error)
	Save(req request.UserLevelsCreateRequest) (err error)
	Update(id uint, req request.UserLevelsUpdateRequest) (err error)
	Delete(id uint) error
}

// NewUserLevelsService init UserLevelsService
func NewUserLevelsService(repo repository.UserLevelsRepository, log zerolog.Logger) UserLevelsService {

	return &userLevelsService{
		Repo: repo,
		Log:  log,
	}
}

// All implement interface of UserLevelsService
func (_i *userLevelsService) All(req request.UserLevelsQueryRequest) (userLevelss []*response.UserLevelsResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, result := range results {
		userLevelss = append(userLevelss, mapper.UserLevelsResponseMapper(result))
	}

	return
}

func (_i *userLevelsService) Show(id uint) (userLevels *response.UserLevelsResponse, err error) {
	result, err := _i.Repo.FindOne(id)
	if err != nil {
		return nil, err
	}

	return mapper.UserLevelsResponseMapper(result), nil
}

func (_i *userLevelsService) Save(req request.UserLevelsCreateRequest) (err error) {
	_i.Log.Info().Interface("data", req).Msg("")

	return _i.Repo.Create(req.ToEntity())
}

func (_i *userLevelsService) Update(id uint, req request.UserLevelsUpdateRequest) (err error) {
	_i.Log.Info().Interface("data", req).Msg("")
	return _i.Repo.Update(id, req.ToEntity())
}

func (_i *userLevelsService) Delete(id uint) error {
	result, err := _i.Repo.FindOne(id)
	if err != nil {
		return err
	}

	isActive := false
	result.IsActive = &isActive
	return _i.Repo.Update(id, result)
}
