package repository

import (
	"campaign-pool-be/app/database"
	"campaign-pool-be/app/database/entity"
	"campaign-pool-be/utils/paginator"

	"github.com/rs/zerolog"
)

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

// EbookWishlistsRepository define interface of IEbookWishlistsRepository
type EbookWishlistsRepository interface {
	GetByUserId(userId uint, pagination *paginator.Pagination) (wishlists []*entity.EbookWishlists, paging paginator.Pagination, err error)
	FindByUserAndEbook(userId uint, ebookId uint) (wishlist *entity.EbookWishlists, err error)
	Create(wishlist *entity.EbookWishlists) (wishlistReturn *entity.EbookWishlists, err error)
	Delete(id uint) (err error)
	DeleteByUserAndEbook(userId uint, ebookId uint) (err error)
}

func NewEbookWishlistsRepository(db *database.Database, log zerolog.Logger) EbookWishlistsRepository {
	return &ebookWishlistsRepository{
		DB:  db,
		Log: log,
	}
}

func (_i *ebookWishlistsRepository) GetByUserId(userId uint, pagination *paginator.Pagination) (wishlists []*entity.EbookWishlists, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.EbookWishlists{}).
		Preload("Ebook").
		Preload("Ebook.Author").
		Where("user_id = ?", userId)

	query.Count(&count)

	pagination.Count = count
	pagination = paginator.Paging(pagination)

	err = query.Offset(pagination.Offset).Limit(pagination.Limit).
		Order("created_at DESC").
		Find(&wishlists).Error
	if err != nil {
		return
	}

	paging = *pagination

	return
}

func (_i *ebookWishlistsRepository) FindByUserAndEbook(userId uint, ebookId uint) (wishlist *entity.EbookWishlists, err error) {
	query := _i.DB.DB.Where("user_id = ? AND ebook_id = ?", userId, ebookId)

	if err := query.First(&wishlist).Error; err != nil {
		return nil, err
	}

	return wishlist, nil
}

func (_i *ebookWishlistsRepository) Create(wishlist *entity.EbookWishlists) (wishlistReturn *entity.EbookWishlists, err error) {
	result := _i.DB.DB.Create(wishlist)
	return wishlist, result.Error
}

func (_i *ebookWishlistsRepository) Delete(id uint) error {
	return _i.DB.DB.Delete(&entity.EbookWishlists{}, id).Error
}

func (_i *ebookWishlistsRepository) DeleteByUserAndEbook(userId uint, ebookId uint) error {
	return _i.DB.DB.Where("user_id = ? AND ebook_id = ?", userId, ebookId).
		Delete(&entity.EbookWishlists{}).Error
}
