package service

import (
	"mime/multipart"

	"github.com/rs/zerolog"

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

type ourServiceContentImagesService struct {
	Repo         repository.OurServiceContentImagesRepository
	MinioStorage *minioStorage.MinioStorage
	Log          zerolog.Logger
}

type OurServiceContentImagesService interface {
	FindByContentID(contentID uint) ([]entity.OurServiceContentImage, error)
	Save(data *entity.OurServiceContentImage) (*entity.OurServiceContentImage, error)
	SaveWithFile(ourServiceContentID uint, file *multipart.FileHeader) (*entity.OurServiceContentImage, error)
	Update(id uint, data *entity.OurServiceContentImage) error
	UpdateWithFile(id uint, file *multipart.FileHeader) error
	Delete(id uint) error
}

func NewOurServiceContentImagesService(
	repo repository.OurServiceContentImagesRepository,
	minio *minioStorage.MinioStorage,
	log zerolog.Logger,
) OurServiceContentImagesService {
	return &ourServiceContentImagesService{
		Repo:         repo,
		MinioStorage: minio,
		Log:          log,
	}
}

func (s *ourServiceContentImagesService) FindByContentID(contentID uint) ([]entity.OurServiceContentImage, error) {
	data, err := s.Repo.FindByContentID(contentID)
	if err != nil {
		s.Log.Error().Err(err).Msg("failed get our service content images")
		return nil, err
	}

	return data, nil
}

func (s *ourServiceContentImagesService) Save(data *entity.OurServiceContentImage) (*entity.OurServiceContentImage, error) {
	result, err := s.Repo.Create(data)
	if err != nil {
		s.Log.Error().Err(err).Msg("failed create our service content image")
		return nil, err
	}

	return result, nil
}

func (s *ourServiceContentImagesService) SaveWithFile(ourServiceContentID uint, file *multipart.FileHeader) (*entity.OurServiceContentImage, error) {
	key, url, err := storage.UploadCMSObject(s.MinioStorage, "our-services", file, false)
	if err != nil {
		return nil, err
	}
	data := &entity.OurServiceContentImage{
		OurServiceContentID: ourServiceContentID,
		ImagePath:           key,
		ImageURL:            url,
	}
	return s.Save(data)
}

func (s *ourServiceContentImagesService) Update(id uint, data *entity.OurServiceContentImage) error {
	err := s.Repo.Update(id, data)
	if err != nil {
		s.Log.Error().Err(err).Msg("failed update our service content image")
		return err
	}

	return nil
}

func (s *ourServiceContentImagesService) UpdateWithFile(id uint, file *multipart.FileHeader) error {
	key, url, err := storage.UploadCMSObject(s.MinioStorage, "our-services", file, false)
	if err != nil {
		return err
	}
	return s.Repo.Update(id, &entity.OurServiceContentImage{
		ImagePath: key,
		ImageURL:  url,
	})
}

func (s *ourServiceContentImagesService) Delete(id uint) error {
	err := s.Repo.Delete(id)
	if err != nil {
		s.Log.Error().Err(err).Msg("failed delete our service content image")
		return err
	}

	return nil
}
