package service

import (
	"mime/multipart"

	"github.com/google/uuid"
	"github.com/rs/zerolog"

	"web-qudo-be/app/database/entity"
	"web-qudo-be/app/module/partner_contents/repository"
	minioStorage "web-qudo-be/config/config"
	"web-qudo-be/utils/storage"
)

type partnerContentService struct {
	Repo         repository.PartnerContentRepository
	MinioStorage *minioStorage.MinioStorage
	Log          zerolog.Logger
}

type PartnerContentService interface {
	Show() ([]entity.PartnerContent, error)
	Save(data *entity.PartnerContent) (*entity.PartnerContent, error)
	Update(id uuid.UUID, data *entity.PartnerContent) error
	UploadLogo(id uuid.UUID, file *multipart.FileHeader) error
	Delete(id uuid.UUID) error
}

func NewPartnerContentService(
	repo repository.PartnerContentRepository,
	minio *minioStorage.MinioStorage,
	log zerolog.Logger,
) PartnerContentService {
	return &partnerContentService{
		Repo:         repo,
		MinioStorage: minio,
		Log:          log,
	}
}

func (s *partnerContentService) Show() ([]entity.PartnerContent, error) {
	data, err := s.Repo.Get()
	if err != nil {
		s.Log.Error().Err(err).Msg("failed get partner content")
		return nil, err
	}

	return data, nil
}

func (s *partnerContentService) Save(data *entity.PartnerContent) (*entity.PartnerContent, error) {
	data.ID = uuid.New()

	result, err := s.Repo.Create(data)
	if err != nil {
		s.Log.Error().Err(err).Msg("failed create partner content")
		return nil, err
	}

	return result, nil
}

func (s *partnerContentService) Update(id uuid.UUID, data *entity.PartnerContent) error {
	err := s.Repo.Update(id, data)
	if err != nil {
		s.Log.Error().Err(err).Msg("failed update partner content")
		return err
	}

	return nil
}

func (s *partnerContentService) UploadLogo(id uuid.UUID, file *multipart.FileHeader) error {
	key, url, err := storage.UploadCMSObject(s.MinioStorage, "partners", file, false)
	if err != nil {
		return err
	}
	return s.Repo.UpdateImageFields(id, key, url)
}

func (s *partnerContentService) Delete(id uuid.UUID) error {
	err := s.Repo.Delete(id)
	if err != nil {
		s.Log.Error().Err(err).Msg("failed delete partner content")
		return err
	}

	return nil
}