package service

import (
	"campaign-pool-be/app/module/districts/mapper"
	"campaign-pool-be/app/module/districts/repository"
	"campaign-pool-be/app/module/districts/request"
	"campaign-pool-be/app/module/districts/response"
	"campaign-pool-be/utils/paginator"

	"github.com/rs/zerolog"
)

// DistrictsService
type districtsService struct {
	Repo repository.DistrictsRepository
	Log  zerolog.Logger
}

// DistrictsService define interface of IDistrictsService
type DistrictsService interface {
	All(req request.DistrictsQueryRequest) (districts []*response.DistrictsResponse, paging paginator.Pagination, err error)
	Show(id uint) (districts *response.DistrictsResponse, err error)
	Save(req request.DistrictsCreateRequest) (err error)
	Update(id uint, req request.DistrictsUpdateRequest) (err error)
	Delete(id uint) error
}

// NewDistrictsService init DistrictsService
func NewDistrictsService(repo repository.DistrictsRepository, log zerolog.Logger) DistrictsService {

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

// All implement interface of DistrictsService
func (_i *districtsService) All(req request.DistrictsQueryRequest) (districtss []*response.DistrictsResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, result := range results {
		districtss = append(districtss, mapper.DistrictsResponseMapper(result))
	}

	return
}

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

	return mapper.DistrictsResponseMapper(result), nil
}

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

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

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

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