package repository

import (
	"web-qudo-be/app/database"
	"web-qudo-be/app/database/entity"
	"web-qudo-be/app/module/popup_news_contents/request"
	"web-qudo-be/utils/paginator"
)

type popupNewsContentsRepository struct {
	DB *database.Database
}

type PopupNewsContentsRepository interface {
	GetAll(req request.PopupNewsContentsQueryRequest) (data []*entity.PopupNewsContents, paging paginator.Pagination, err error)
	FindOne(id uint) (*entity.PopupNewsContents, error)
	Create(data *entity.PopupNewsContents) error
	Update(id uint, data *entity.PopupNewsContents) error
	Delete(id uint) error
}

func NewPopupNewsContentsRepository(db *database.Database) PopupNewsContentsRepository {
	return &popupNewsContentsRepository{
		DB: db,
	}
}

// Get All + 🔥 Preload Images
func (_i *popupNewsContentsRepository) GetAll(req request.PopupNewsContentsQueryRequest) (datas []*entity.PopupNewsContents, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.PopupNewsContents{}).
		Preload("Images") // 🔥 penting

	query.Count(&count)

	req.Pagination.Count = count
	req.Pagination = paginator.Paging(req.Pagination)

	err = query.
		Offset(req.Pagination.Offset).
		Limit(req.Pagination.Limit).
		Find(&datas).Error
	if err != nil {
		return
	}

	paging = *req.Pagination
	return
}

// Find One + 🔥 Preload Images
func (_i *popupNewsContentsRepository) FindOne(id uint) (*entity.PopupNewsContents, error) {
	var data entity.PopupNewsContents

	if err := _i.DB.DB.
		Preload("Images").
		First(&data, id).Error; err != nil {
		return nil, err
	}

	return &data, nil
}

// Create
func (_i *popupNewsContentsRepository) Create(data *entity.PopupNewsContents) error {
	return _i.DB.DB.Create(data).Error
}

// Update
func (_i *popupNewsContentsRepository) Update(id uint, data *entity.PopupNewsContents) error {
	return _i.DB.DB.Model(&entity.PopupNewsContents{}).
		Where(&entity.PopupNewsContents{ID: id}).
		Updates(data).Error
}

// Delete
func (_i *popupNewsContentsRepository) Delete(id uint) error {
	return _i.DB.DB.Delete(&entity.PopupNewsContents{}, id).Error
}