package service

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

// MasterMenusService
type masterMenusService struct {
	Repo repository.MasterMenusRepository
	Log  zerolog.Logger
}

// MasterMenusService define interface of IMasterMenusService
type MasterMenusService interface {
	All(req request.MasterMenusQueryRequest) (masterMenus []*response.MasterMenusResponse, paging paginator.Pagination, err error)
	Show(id uint) (masterMenus *response.MasterMenusResponse, err error)
	Save(req request.MasterMenusCreateRequest) (err error)
	Update(id uint, req request.MasterMenusUpdateRequest) (err error)
	Delete(id uint) error
}

// NewMasterMenusService init MasterMenusService
func NewMasterMenusService(repo repository.MasterMenusRepository, log zerolog.Logger) MasterMenusService {

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

// All implement interface of MasterMenusService
func (_i *masterMenusService) All(req request.MasterMenusQueryRequest) (masterMenuss []*response.MasterMenusResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, result := range results {
		masterMenuss = append(masterMenuss, mapper.MasterMenusResponseMapper(result))
	}

	return
}

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

	return mapper.MasterMenusResponseMapper(result), nil
}

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

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

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

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