package service

import (
	"mime/multipart"

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

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

type heroContentImagesService struct {
	Repo         repository.HeroContentImagesRepository
	MinioStorage *minioStorage.MinioStorage
	Log          zerolog.Logger
}

type HeroContentImagesService interface {
	FindByHeroID(heroID uuid.UUID) (*entity.HeroContentImages, error)
	Save(data *entity.HeroContentImages) (*entity.HeroContentImages, error)
	SaveWithFile(heroContentID uuid.UUID, file *multipart.FileHeader) (*entity.HeroContentImages, error)
	Update(id uuid.UUID, data *entity.HeroContentImages) error
	UpdateWithFile(id uuid.UUID, file *multipart.FileHeader) error
	Delete(id uuid.UUID) error
}

func NewHeroContentImagesService(
	repo repository.HeroContentImagesRepository,
	minio *minioStorage.MinioStorage,
	log zerolog.Logger,
) HeroContentImagesService {
	return &heroContentImagesService{
		Repo:         repo,
		MinioStorage: minio,
		Log:          log,
	}
}

func (s *heroContentImagesService) FindByHeroID(heroID uuid.UUID) (*entity.HeroContentImages, error) {
	data, err := s.Repo.FindByHeroID(heroID)
	if err != nil {
		s.Log.Error().Err(err).Msg("failed get hero content image")
		return nil, err
	}

	return data, nil
}

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

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

	return result, nil
}

func (s *heroContentImagesService) SaveWithFile(heroContentID uuid.UUID, file *multipart.FileHeader) (*entity.HeroContentImages, error) {
	key, url, err := storage.UploadCMSObject(s.MinioStorage, "hero", file, false)
	if err != nil {
		return nil, err
	}
	data := &entity.HeroContentImages{
		HeroContentID: heroContentID,
		ImagePath:     key,
		ImageURL:      url,
	}
	return s.Save(data)
}

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

	return nil
}

func (s *heroContentImagesService) UpdateWithFile(id uuid.UUID, file *multipart.FileHeader) error {
	key, url, err := storage.UploadCMSObject(s.MinioStorage, "hero", file, false)
	if err != nil {
		return err
	}
	return s.Repo.Update(id, &entity.HeroContentImages{
		ImagePath: key,
		ImageURL:  url,
	})
}

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

	return nil
}
