package service

import "gorm.io/gorm"

func checkPageParam(page, pageSize int) (int, int) {
	retPage := 0
	retPageSize := 0

	if page <= 0 {
		retPage = 1
	} else {
		retPage = page
	}

	if pageSize <= 0 {
		retPageSize = 20
	} else if pageSize > 100 {
		retPageSize = 100
	} else {
		retPageSize = pageSize
	}

	return retPage, retPageSize
}

type PaginationResult struct {
	Count int64
	Limit func(db *gorm.DB) *gorm.DB
}

func Paginate(db *gorm.DB, page int, size int) *PaginationResult {
	var count int64
	db.Count(&count)

	limit := func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case size > 100:
			size = 100
		case size <= 0:
			size = 10
		}

		return db.Offset((page - 1) * size).Limit(size)
	}

	return &PaginationResult{
		Count: count,
		Limit: limit,
	}
}
