package repository

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

type magazineFilesRepository struct {
	DB *database.Database
}

// MagazineFilesRepository define interface of IMagazineFilesRepository
type MagazineFilesRepository interface {
	GetAll(req request.MagazineFilesQueryRequest) (magazineFiless []*entity.MagazineFiles, paging paginator.Pagination, err error)
	FindOne(id uint) (magazineFiles *entity.MagazineFiles, err error)
	Create(magazineFiles *entity.MagazineFiles) (err error)
	Update(id uint, magazineFiles *entity.MagazineFiles) (err error)
	Delete(id uint) (err error)
}

func NewMagazineFilesRepository(db *database.Database) MagazineFilesRepository {
	return &magazineFilesRepository{
		DB: db,
	}
}

// implement interface of IMagazineFilesRepository
func (_i *magazineFilesRepository) GetAll(req request.MagazineFilesQueryRequest) (magazineFiless []*entity.MagazineFiles, paging paginator.Pagination, err error) {
	var count int64

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

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

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

	paging = *req.Pagination

	return
}

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

	return magazineFiles, nil
}

func (_i *magazineFilesRepository) Create(magazineFiles *entity.MagazineFiles) (err error) {
	return _i.DB.DB.Create(magazineFiles).Error
}

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

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