package repository

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

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

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

type HeroContentsRepository interface {
	Get() (*entity.HeroContents, error)
	Create(data *entity.HeroContents) (*entity.HeroContents, error)
	Update(id uuid.UUID, data *entity.HeroContents) error
	Delete(id uuid.UUID) error
}

func NewHeroContentsRepository(db *database.Database, logger zerolog.Logger) HeroContentsRepository {
	return &heroContentsRepository{
		DB:  db,
		Log: logger,
	}
}

func (r *heroContentsRepository) Get() (*entity.HeroContents, error) {
	var data entity.HeroContents

	err := r.DB.DB.
		Preload("HeroContentImage").
		First(&data).Error

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

	return &data, nil
}

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

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

	return data, nil
}

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

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

	return nil
}

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

	return nil
}