package service

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

// MasterModulesService
type masterModulesService struct {
	Repo repository.MasterModulesRepository
	Log  zerolog.Logger
}

// MasterModulesService define interface of IMasterModulesService
type MasterModulesService interface {
	All(req request.MasterModulesQueryRequest) (masterModules []*response.MasterModulesResponse, paging paginator.Pagination, err error)
	Show(id uint) (masterModules *response.MasterModulesResponse, err error)
	Save(req request.MasterModulesCreateRequest) (err error)
	Update(id uint, req request.MasterModulesUpdateRequest) (err error)
	Delete(id uint) error
}

// NewMasterModulesService init MasterModulesService
func NewMasterModulesService(repo repository.MasterModulesRepository, log zerolog.Logger) MasterModulesService {

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

// All implement interface of MasterModulesService
func (_i *masterModulesService) All(req request.MasterModulesQueryRequest) (masterModuless []*response.MasterModulesResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, result := range results {
		masterModuless = append(masterModuless, mapper.MasterModulesResponseMapper(result))
	}

	return
}

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

	return mapper.MasterModulesResponseMapper(result), nil
}

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

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

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

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