package repository

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

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

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

type OurServiceContentRepository interface {
	Get() (*entity.OurServiceContent, error)
	GetAll() ([]entity.OurServiceContent, error)
	Create(data *entity.OurServiceContent) (*entity.OurServiceContent, error)
	Update(id uint, data *entity.OurServiceContent) error
	Delete(id uint) error
}

func NewOurServiceContentRepository(db *database.Database, logger zerolog.Logger) OurServiceContentRepository {
	return &ourServiceContentRepository{
		DB:  db,
		Log: logger,
	}
}

func (r *ourServiceContentRepository) Get() (*entity.OurServiceContent, error) {
	var data entity.OurServiceContent

	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 service content")
		return nil, err
	}

	return &data, nil
}

func (r *ourServiceContentRepository) GetAll() ([]entity.OurServiceContent, error) {
	var rows []entity.OurServiceContent
	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 service contents")
		return nil, err
	}
	return rows, nil
}

func (r *ourServiceContentRepository) Create(data *entity.OurServiceContent) (*entity.OurServiceContent, error) {
	err := r.DB.DB.Create(data).Error
	if err != nil {
		r.Log.Error().Err(err).Msg("failed create our service content")
		return nil, err
	}

	return data, nil
}

func (r *ourServiceContentRepository) Update(id uint, data *entity.OurServiceContent) error {
	err := r.DB.DB.
		Model(&entity.OurServiceContent{}).
		Where("id = ?", id).
		Updates(data).Error

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

	return nil
}

func (r *ourServiceContentRepository) Delete(id uint) error {
	err := r.DB.DB.Delete(&entity.OurServiceContent{}, id).Error
	if err != nil {
		r.Log.Error().Err(err).Msg("failed delete our service content")
		return err
	}

	return nil
}