package repository

import (
	"web-qudo-be/app/database"
	"web-qudo-be/app/database/entity"

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

type heroContentImagesRepository struct {
	DB  *database.Database
	Log zerolog.Logger
}

type HeroContentImagesRepository interface {
	FindByHeroID(heroID uuid.UUID) (*entity.HeroContentImages, error)
	Create(data *entity.HeroContentImages) (*entity.HeroContentImages, error)
	Update(id uuid.UUID, data *entity.HeroContentImages) error
	Delete(id uuid.UUID) error
}

func NewHeroContentImagesRepository(db *database.Database, log zerolog.Logger) HeroContentImagesRepository {
	return &heroContentImagesRepository{
		DB:  db,
		Log: log,
	}
}

func (r *heroContentImagesRepository) FindByHeroID(heroID uuid.UUID) (*entity.HeroContentImages, error) {
	var data entity.HeroContentImages

	err := r.DB.DB.
		Where("hero_content_id = ?", heroID).
		First(&data).Error

	if err != nil {
		r.Log.Error().Err(err).Msg("failed get hero content image")
		return nil, err
	}

	return &data, nil
}

func (r *heroContentImagesRepository) Create(data *entity.HeroContentImages) (*entity.HeroContentImages, error) {
	data.ID = uuid.New()

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

	return data, nil
}

func (r *heroContentImagesRepository) Update(id uuid.UUID, data *entity.HeroContentImages) error {
	err := r.DB.DB.
		Model(&entity.HeroContentImages{}).
		Where("id = ?", id).
		Updates(data).Error

	if err != nil {
		r.Log.Error().Err(err).Msg("failed update hero content image")
		return err
	}

	return nil
}

func (r *heroContentImagesRepository) Delete(id uuid.UUID) error {
	err := r.DB.DB.Delete(&entity.HeroContentImages{}, id).Error
	if err != nil {
		r.Log.Error().Err(err).Msg("failed delete hero content image")
		return err
	}

	return nil
}