package service

import (
	"narasi-ahli-be/app/database/entity"
	"narasi-ahli-be/app/module/subscription/mapper"
	"narasi-ahli-be/app/module/subscription/repository"
	"narasi-ahli-be/app/module/subscription/request"
	"narasi-ahli-be/app/module/subscription/response"
	usersRepository "narasi-ahli-be/app/module/users/repository"
	"narasi-ahli-be/utils/paginator"

	"github.com/rs/zerolog"
)

// SubscriptionService
type subscriptionService struct {
	Repo      repository.SubscriptionRepository
	UsersRepo usersRepository.UsersRepository
	Log       zerolog.Logger
}

// SubscriptionService define interface of ISubscriptionService
type SubscriptionService interface {
	All(req request.SubscriptionQueryRequest) (subscription []*response.SubscriptionResponse, paging paginator.Pagination, err error)
	Show(id uint) (subscription *response.SubscriptionResponse, err error)
	Save(req request.SubscriptionCreateRequest) (subscription *entity.Subscription, err error)
	Update(id uint, req request.SubscriptionUpdateRequest) (err error)
	Delete(id uint) error
}

// NewSubscriptionService init SubscriptionService
func NewSubscriptionService(repo repository.SubscriptionRepository, log zerolog.Logger, usersRepo usersRepository.UsersRepository) SubscriptionService {

	return &subscriptionService{
		Repo:      repo,
		Log:       log,
		UsersRepo: usersRepo,
	}
}

// All implement interface of SubscriptionService
func (_i *subscriptionService) All(req request.SubscriptionQueryRequest) (subscriptions []*response.SubscriptionResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, result := range results {
		subscriptions = append(subscriptions, mapper.SubscriptionResponseMapper(result))
	}

	return
}

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

	return mapper.SubscriptionResponseMapper(result), nil
}

func (_i *subscriptionService) Save(req request.SubscriptionCreateRequest) (subscription *entity.Subscription, err error) {
	_i.Log.Info().Interface("data", req).Msg("")
	newReq := req.ToEntity()

	return _i.Repo.Create(newReq)
}

func (_i *subscriptionService) Update(id uint, req request.SubscriptionUpdateRequest) (err error) {
	_i.Log.Info().Interface("data", req).Msg("")

	entity := req.ToEntity()

	return _i.Repo.Update(id, entity)
}

func (_i *subscriptionService) Delete(id uint) error {
	result, err := _i.Repo.FindOne(id)
	if err != nil {
		return err
	}

	result.IsActive = false
	return _i.Repo.Update(id, result)
}
