package service

import (
	"narasi-ahli-be/app/module/provinces/mapper"
	"narasi-ahli-be/app/module/provinces/repository"
	"narasi-ahli-be/app/module/provinces/request"
	"narasi-ahli-be/app/module/provinces/response"
	"narasi-ahli-be/utils/paginator"

	"github.com/rs/zerolog"
)

// ProvincesService
type provincesService struct {
	Repo repository.ProvincesRepository
	Log  zerolog.Logger
}

// ProvincesService define interface of IProvincesService
type ProvincesService interface {
	All(req request.ProvincesQueryRequest) (provinces []*response.ProvincesResponse, paging paginator.Pagination, err error)
	Show(id uint) (provinces *response.ProvincesResponse, err error)
	Save(req request.ProvincesCreateRequest) (err error)
	Update(id uint, req request.ProvincesUpdateRequest) (err error)
	Delete(id uint) error
}

// NewProvincesService init ProvincesService
func NewProvincesService(repo repository.ProvincesRepository, log zerolog.Logger) ProvincesService {

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

// All implement interface of ProvincesService
func (_i *provincesService) All(req request.ProvincesQueryRequest) (provincess []*response.ProvincesResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, result := range results {
		provincess = append(provincess, mapper.ProvincesResponseMapper(result))
	}

	return
}

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

	return mapper.ProvincesResponseMapper(result), nil
}

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

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

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

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