package service

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

// CitiesService
type citiesService struct {
	Repo repository.CitiesRepository
	Log  zerolog.Logger
}

// CitiesService define interface of ICitiesService
type CitiesService interface {
	All(req request.CitiesQueryRequest) (cities []*response.CitiesResponse, paging paginator.Pagination, err error)
	Show(id uint) (cities *response.CitiesResponse, err error)
	Save(req request.CitiesCreateRequest) (err error)
	Update(id uint, req request.CitiesUpdateRequest) (err error)
	Delete(id uint) error
}

// NewCitiesService init CitiesService
func NewCitiesService(repo repository.CitiesRepository, log zerolog.Logger) CitiesService {

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

// All implement interface of CitiesService
func (_i *citiesService) All(req request.CitiesQueryRequest) (citiess []*response.CitiesResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, result := range results {
		citiess = append(citiess, mapper.CitiesResponseMapper(result))
	}

	return
}

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

	return mapper.CitiesResponseMapper(result), nil
}

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

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

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

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