package service

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

// UserRoleAccessesService
type userRoleAccessesService struct {
	Repo repository.UserRoleAccessesRepository
	Log  zerolog.Logger
}

// UserRoleAccessesService define interface of IUserRoleAccessesService
type UserRoleAccessesService interface {
	All(req request.UserRoleAccessesQueryRequest) (userRoleAccesses []*response.UserRoleAccessesResponse, paging paginator.Pagination, err error)
	Show(id uint) (userRoleAccesses *response.UserRoleAccessesResponse, err error)
	Save(req request.UserRoleAccessesCreateRequest) (err error)
	Update(id uint, req request.UserRoleAccessesUpdateRequest) (err error)
	Delete(id uint) error
}

// NewUserRoleAccessesService init UserRoleAccessesService
func NewUserRoleAccessesService(repo repository.UserRoleAccessesRepository, log zerolog.Logger) UserRoleAccessesService {

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

// All implement interface of UserRoleAccessesService
func (_i *userRoleAccessesService) All(req request.UserRoleAccessesQueryRequest) (userRoleAccessess []*response.UserRoleAccessesResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, result := range results {
		userRoleAccessess = append(userRoleAccessess, mapper.UserRoleAccessesResponseMapper(result))
	}

	return
}

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

	return mapper.UserRoleAccessesResponseMapper(result), nil
}

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

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

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

func (_i *userRoleAccessesService) 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)
}
