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 ourProductContentRepository struct {
	DB  *database.Database
	Log zerolog.Logger
}

type OurProductContentRepository interface {
	Get() (*entity.OurProductContent, error)
	GetAll() ([]entity.OurProductContent, error)
	Create(data *entity.OurProductContent) (*entity.OurProductContent, error)
	Update(id uuid.UUID, data *entity.OurProductContent) error
	Delete(id uuid.UUID) error
}

func NewOurProductContentRepository(db *database.Database, logger zerolog.Logger) OurProductContentRepository {
	return &ourProductContentRepository{
		DB:  db,
		Log: logger,
	}
}

func (r *ourProductContentRepository) Get() (*entity.OurProductContent, error) {
	var data entity.OurProductContent

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

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

	return &data, nil
}

func (r *ourProductContentRepository) GetAll() ([]entity.OurProductContent, error) {
	var rows []entity.OurProductContent
	err := r.DB.DB.
		Preload("Images").
		Order("created_at ASC").
		Find(&rows).Error
	if err != nil {
		r.Log.Error().Err(err).Msg("failed list our product contents")
		return nil, err
	}
	return rows, nil
}

func (r *ourProductContentRepository) Create(data *entity.OurProductContent) (*entity.OurProductContent, 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")
		return nil, err
	}

	return data, nil
}

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

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

	return nil
}

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

	return nil
}