package service

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

// MagazinesService
type magazinesService struct {
	Repo repository.MagazinesRepository
	Log  zerolog.Logger
}

// MagazinesService define interface of IMagazinesService
type MagazinesService interface {
	All(req request.MagazinesQueryRequest) (magazines []*response.MagazinesResponse, paging paginator.Pagination, err error)
	Show(id uint) (magazines *response.MagazinesResponse, err error)
	Save(req request.MagazinesCreateRequest) (err error)
	Update(id uint, req request.MagazinesUpdateRequest) (err error)
	Delete(id uint) error
}

// NewMagazinesService init MagazinesService
func NewMagazinesService(repo repository.MagazinesRepository, log zerolog.Logger) MagazinesService {

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

// All implement interface of MagazinesService
func (_i *magazinesService) All(req request.MagazinesQueryRequest) (magaziness []*response.MagazinesResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, result := range results {
		magaziness = append(magaziness, mapper.MagazinesResponseMapper(result))
	}

	return
}

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

	return mapper.MagazinesResponseMapper(result), nil
}

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

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

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

func (_i *magazinesService) Delete(id uint) error {
	return _i.Repo.Delete(id)
}
