package service

import (
	"campaign-pool-be/app/database/entity"
	"campaign-pool-be/app/module/campaign_files/mapper"
	"campaign-pool-be/app/module/campaign_files/repository"
	"campaign-pool-be/app/module/campaign_files/request"
	"campaign-pool-be/app/module/campaign_files/response"
	usersRepository "campaign-pool-be/app/module/users/repository"
	config "campaign-pool-be/config/config"
	"campaign-pool-be/utils/paginator"

	"github.com/rs/zerolog"
)

type campaignFilesService struct {
	Repo      repository.CampaignFilesRepository
	UsersRepo usersRepository.UsersRepository
	Log       zerolog.Logger
	Cfg       *config.Config
}

type CampaignFilesService interface {
	All(req request.CampaignFilesQueryRequest, authToken string) (campaignFiles []*response.CampaignFilesResponse, paging paginator.Pagination, err error)
	Show(id uint) (campaignFiles *response.CampaignFilesResponse, err error)
	GetByCampaign(campaignID uint) (campaignFiles []*response.CampaignFilesResponse, err error)
	Save(req request.CampaignFilesCreateRequest, authToken string) (campaignFiles *entity.CampaignFiles, err error)
	Update(id uint, req request.CampaignFilesUpdateRequest) (err error)
	Delete(id uint) error
}

func NewCampaignFilesService(repo repository.CampaignFilesRepository, usersRepo usersRepository.UsersRepository, log zerolog.Logger, cfg *config.Config) CampaignFilesService {
	return &campaignFilesService{
		Repo:      repo,
		UsersRepo: usersRepo,
		Log:       log,
		Cfg:       cfg,
	}
}

func (_i *campaignFilesService) All(req request.CampaignFilesQueryRequest, authToken string) (campaignFiless []*response.CampaignFilesResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, result := range results {
		campaignFiless = append(campaignFiless, mapper.CampaignFilesResponseMapper(result))
	}
	return
}

func (_i *campaignFilesService) Show(id uint) (campaignFiles *response.CampaignFilesResponse, err error) {
	result, err := _i.Repo.FindOne(id)
	if err != nil {
		return nil, err
	}
	return mapper.CampaignFilesResponseMapper(result), nil
}

func (_i *campaignFilesService) GetByCampaign(campaignID uint) (campaignFiless []*response.CampaignFilesResponse, err error) {
	results, err := _i.Repo.FindByCampaign(campaignID)
	if err != nil {
		return nil, err
	}

	for _, result := range results {
		campaignFiless = append(campaignFiless, mapper.CampaignFilesResponseMapper(result))
	}
	return
}

func (_i *campaignFilesService) Save(req request.CampaignFilesCreateRequest, authToken string) (campaignFiles *entity.CampaignFiles, err error) {
	newReq := req.ToEntity()
	return _i.Repo.Create(newReq)
}

func (_i *campaignFilesService) Update(id uint, req request.CampaignFilesUpdateRequest) (err error) {
	newReq := req.ToEntity()
	return _i.Repo.Update(id, newReq)
}

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

