package repository

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

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

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

type OurProductContentImagesRepository interface {
	FindByContentID(contentID uuid.UUID) ([]entity.OurProductContentImage, error)
	Create(data *entity.OurProductContentImage) (*entity.OurProductContentImage, error)
	Update(id uuid.UUID, data *entity.OurProductContentImage) error
	Delete(id uuid.UUID) error
}

func NewOurProductContentImagesRepository(db *database.Database, log zerolog.Logger) OurProductContentImagesRepository {
	return &ourProductContentImagesRepository{
		DB:  db,
		Log: log,
	}
}

func (r *ourProductContentImagesRepository) FindByContentID(contentID uuid.UUID) ([]entity.OurProductContentImage, error) {
	var data []entity.OurProductContentImage

	err := r.DB.DB.
		Where("our_product_content_id = ?", contentID).
		Find(&data).Error

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

	return data, nil
}

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

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

	return data, nil
}

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

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

	return nil
}

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

	return nil
}