package service

import (
	"fmt"
	"mime/multipart"
	"path/filepath"
	"time"
	"web-qudo-be/app/database/entity"
	"web-qudo-be/app/module/about_us_content_images/repository"

	"github.com/rs/zerolog"

	fileUtil "web-qudo-be/utils/file"
)

type aboutUsContentImageService struct {
	Repo repository.AboutUsContentImageRepository
	Log  zerolog.Logger
}

type AboutUsContentImageService interface {
	All() (images []*entity.AboutUsContentImage, err error)
	Show(id uint) (image *entity.AboutUsContentImage, err error)
	Save(aboutUsContentId uint, file *multipart.FileHeader) (image *entity.AboutUsContentImage, err error)
	Delete(id uint) error
}

func NewAboutUsContentImageService(
	repo repository.AboutUsContentImageRepository,
	log zerolog.Logger,
) AboutUsContentImageService {
	return &aboutUsContentImageService{
		Repo: repo,
		Log:  log,
	}
}

func (_i *aboutUsContentImageService) All() (images []*entity.AboutUsContentImage, err error) {
	return _i.Repo.GetAll()
}

func (_i *aboutUsContentImageService) Show(id uint) (image *entity.AboutUsContentImage, err error) {
	return _i.Repo.FindOne(id)
}

func (_i *aboutUsContentImageService) Save(aboutUsContentId uint, file *multipart.FileHeader) (image *entity.AboutUsContentImage, err error) {

	_i.Log.Info().
		Uint("aboutUsContentId", aboutUsContentId).
		Str("filename", file.Filename).
		Msg("upload image")

	// validasi file
	ext := filepath.Ext(file.Filename)
	if ext != ".jpg" && ext != ".jpeg" && ext != ".png" {
		return nil, fmt.Errorf("invalid file type")
	}

	// generate filename
	filename := fmt.Sprintf("about_us_%d_%d%s", aboutUsContentId, time.Now().Unix(), ext)

	filePath := fmt.Sprintf("./uploads/%s", filename)

	// save file
	if err := fileUtil.SaveFile(file, filePath); err != nil {
		_i.Log.Error().Err(err).Msg("failed save file")
		return nil, err
	}

	// save ke DB
	data := &entity.AboutUsContentImage{
		AboutUsContentID: aboutUsContentId,
		MediaPath:        filePath,
		MediaType:        ext,
		MediaURL:         "/uploads/" + filename,
	}

	result, err := _i.Repo.Create(data)
	if err != nil {
		_i.Log.Error().Err(err).Msg("failed save to DB")
		return nil, err
	}

	return result, nil
}

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



