package repository

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

type articleCategoryDetailsRepository struct {
	DB *database.Database
}

// ArticleCategoryDetailsRepository define interface of IArticleCategoryDetailsRepository
type ArticleCategoryDetailsRepository interface {
	GetAll(req request.ArticleCategoryDetailsQueryRequest) (articleCategoryDetailss []*entity.ArticleCategoryDetails, paging paginator.Pagination, err error)
	FindOne(id uint) (articleCategoryDetails *entity.ArticleCategoryDetails, err error)
	Create(articleCategoryDetails *entity.ArticleCategoryDetails) (err error)
	Update(id uint, articleCategoryDetails *entity.ArticleCategoryDetails) (err error)
	Delete(id uint) (err error)
}

func NewArticleCategoryDetailsRepository(db *database.Database) ArticleCategoryDetailsRepository {
	return &articleCategoryDetailsRepository{
		DB: db,
	}
}

// implement interface of IArticleCategoryDetailsRepository
func (_i *articleCategoryDetailsRepository) GetAll(req request.ArticleCategoryDetailsQueryRequest) (articleCategoryDetailss []*entity.ArticleCategoryDetails, paging paginator.Pagination, err error) {
	var count int64

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

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

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

	paging = *req.Pagination

	return
}

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

	return articleCategoryDetails, nil
}

func (_i *articleCategoryDetailsRepository) Create(articleCategoryDetails *entity.ArticleCategoryDetails) (err error) {
	return _i.DB.DB.Create(articleCategoryDetails).Error
}

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

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