package service

import (
	"mime/multipart"

	"github.com/rs/zerolog"

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

type popupNewsContentImagesService struct {
	Repo         repository.PopupNewsContentImagesRepository
	MinioStorage *minioStorage.MinioStorage
	Log          zerolog.Logger
}

type PopupNewsContentImagesService interface {
	Save(req request.PopupNewsContentImagesCreateRequest) error
	SaveWithFile(popupNewsContentID uint, file *multipart.FileHeader, isThumbnail *bool) (*entity.PopupNewsContentImages, error)
	Delete(id uint) error
}

func NewPopupNewsContentImagesService(
	repo repository.PopupNewsContentImagesRepository,
	minio *minioStorage.MinioStorage,
	log zerolog.Logger,
) PopupNewsContentImagesService {
	return &popupNewsContentImagesService{
		Repo:         repo,
		MinioStorage: minio,
		Log:          log,
	}
}

func (_i *popupNewsContentImagesService) Save(req request.PopupNewsContentImagesCreateRequest) error {
	_i.Log.Info().Interface("data", req).Msg("create popup news content image (json)")

	return _i.Repo.Create(req.ToEntity())
}

func (_i *popupNewsContentImagesService) SaveWithFile(popupNewsContentID uint, file *multipart.FileHeader, isThumbnail *bool) (*entity.PopupNewsContentImages, error) {
	_i.Log.Info().
		Uint("popup_news_content_id", popupNewsContentID).
		Str("filename", file.Filename).
		Msg("upload popup news content image")

	key, url, err := storage.UploadCMSObject(_i.MinioStorage, "popup-news", file, false)
	if err != nil {
		return nil, err
	}

	if isThumbnail != nil && *isThumbnail {
		if err := _i.Repo.ResetThumbnail(popupNewsContentID); err != nil {
			return nil, err
		}
	}

	row := &entity.PopupNewsContentImages{
		PopupNewsContentID: popupNewsContentID,
		MediaPath:          key,
		MediaURL:           url,
		IsThumbnail:        isThumbnail,
	}
	if err := _i.Repo.Create(row); err != nil {
		return nil, err
	}
	return row, nil
}

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