package service

import (
	"jaecoo-be/app/database/entity"
	"jaecoo-be/app/module/approval_histories/mapper"
	"jaecoo-be/app/module/approval_histories/repository"
	"jaecoo-be/app/module/approval_histories/request"
	"jaecoo-be/app/module/approval_histories/response"
	"jaecoo-be/utils/paginator"

	"github.com/rs/zerolog"
)

type approvalHistoriesService struct {
	Repo repository.ApprovalHistoriesRepository
	Log  zerolog.Logger
}

type ApprovalHistoriesService interface {
	GetAll(req request.ApprovalHistoriesQueryRequest) (histories []*response.ApprovalHistoriesResponse, paging paginator.Pagination, err error)
	GetByModule(moduleType string, moduleId uint) (histories []*response.ApprovalHistoriesResponse, err error)
	CreateHistory(moduleType string, moduleId uint, statusId int, action string, approvedBy *uint, message *string) (err error)
}

func NewApprovalHistoriesService(repo repository.ApprovalHistoriesRepository, log zerolog.Logger) ApprovalHistoriesService {
	return &approvalHistoriesService{
		Repo: repo,
		Log:  log,
	}
}

func (_i *approvalHistoriesService) GetAll(req request.ApprovalHistoriesQueryRequest) (histories []*response.ApprovalHistoriesResponse, paging paginator.Pagination, err error) {
	historiesEntity, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, history := range historiesEntity {
		histories = append(histories, mapper.ApprovalHistoriesResponseMapper(history))
	}

	return
}

func (_i *approvalHistoriesService) GetByModule(moduleType string, moduleId uint) (histories []*response.ApprovalHistoriesResponse, err error) {
	historiesEntity, err := _i.Repo.GetByModule(moduleType, moduleId)
	if err != nil {
		return
	}

	for _, history := range historiesEntity {
		histories = append(histories, mapper.ApprovalHistoriesResponseMapper(history))
	}

	return
}

func (_i *approvalHistoriesService) CreateHistory(moduleType string, moduleId uint, statusId int, action string, approvedBy *uint, message *string) (err error) {
	history := &entity.ApprovalHistories{
		ModuleType: moduleType,
		ModuleId:   moduleId,
		StatusId:   statusId,
		Action:     action,
		ApprovedBy: approvedBy,
		Message:    message,
	}

	_, err = _i.Repo.Create(history)
	return
}
