package repository

import (
	"go-humas-be/app/database"
	"go-humas-be/app/database/entity"
	"go-humas-be/app/module/magazines/request"
	"go-humas-be/utils/paginator"
)

type magazinesRepository struct {
	DB *database.Database
}

// MagazinesRepository define interface of IMagazinesRepository
type MagazinesRepository interface {
	GetAll(req request.MagazinesQueryRequest) (magaziness []*entity.Magazines, paging paginator.Pagination, err error)
	FindOne(id uint) (magazines *entity.Magazines, err error)
	Create(magazines *entity.Magazines) (err error)
	Update(id uint, magazines *entity.Magazines) (err error)
	Delete(id uint) (err error)
}

func NewMagazinesRepository(db *database.Database) MagazinesRepository {
	return &magazinesRepository{
		DB: db,
	}
}

// implement interface of IMagazinesRepository
func (_i *magazinesRepository) GetAll(req request.MagazinesQueryRequest) (magaziness []*entity.Magazines, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.Magazines{})
	query.Count(&count)

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

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

	paging = *req.Pagination

	return
}

func (_i *magazinesRepository) FindOne(id uint) (magazines *entity.Magazines, err error) {
	if err := _i.DB.DB.First(&magazines, id).Error; err != nil {
		return nil, err
	}

	return magazines, nil
}

func (_i *magazinesRepository) Create(magazines *entity.Magazines) (err error) {
	return _i.DB.DB.Create(magazines).Error
}

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

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