package repository

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

	"github.com/rs/zerolog"
)

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

// EbookPurchasesRepository define interface of IEbookPurchasesRepository
type EbookPurchasesRepository interface {
	GetByBuyerId(buyerId uint, pagination *paginator.Pagination) (purchases []*entity.EbookPurchases, paging paginator.Pagination, err error)
	FindByBuyerAndEbook(buyerId uint, ebookId uint) (purchase *entity.EbookPurchases, err error)
	FindOne(id uint) (purchase *entity.EbookPurchases, err error)
	Create(purchase *entity.EbookPurchases) (purchaseReturn *entity.EbookPurchases, err error)
	Update(id uint, purchase *entity.EbookPurchases) (err error)
	UpdateDownloadCount(id uint) (err error)
	Delete(id uint) (err error)
}

func NewEbookPurchasesRepository(db *database.Database, log zerolog.Logger) EbookPurchasesRepository {
	return &ebookPurchasesRepository{
		DB:  db,
		Log: log,
	}
}

func (_i *ebookPurchasesRepository) GetByBuyerId(buyerId uint, pagination *paginator.Pagination) (purchases []*entity.EbookPurchases, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.EbookPurchases{}).
		Preload("Ebook").
		Preload("Ebook.Author").
		Preload("Buyer").
		Where("buyer_id = ?", buyerId)

	query.Count(&count)

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

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

	paging = *pagination

	return
}

func (_i *ebookPurchasesRepository) FindByBuyerAndEbook(buyerId uint, ebookId uint) (purchase *entity.EbookPurchases, err error) {
	query := _i.DB.DB.Where("buyer_id = ? AND ebook_id = ?", buyerId, ebookId)

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

	return purchase, nil
}

func (_i *ebookPurchasesRepository) FindOne(id uint) (purchase *entity.EbookPurchases, err error) {
	query := _i.DB.DB.Preload("Ebook").Preload("Buyer")
	if err := query.First(&purchase, id).Error; err != nil {
		return nil, err
	}

	return purchase, nil
}

func (_i *ebookPurchasesRepository) Create(purchase *entity.EbookPurchases) (purchaseReturn *entity.EbookPurchases, err error) {
	result := _i.DB.DB.Create(purchase)
	return purchase, result.Error
}

func (_i *ebookPurchasesRepository) Update(id uint, purchase *entity.EbookPurchases) (err error) {
	return _i.DB.DB.Model(&entity.EbookPurchases{}).
		Where(&entity.EbookPurchases{ID: id}).
		Updates(purchase).Error
}

func (_i *ebookPurchasesRepository) UpdateDownloadCount(id uint) (err error) {
	return _i.DB.DB.Model(&entity.EbookPurchases{}).
		Where("id = ?", id).
		Update("download_count", "download_count + 1").Error
}

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