// Package pagination provides overflow-safe pagination arithmetic shared by
// transports, services, and data stores.
package pagination

import "math"

// PageCount returns the number of pages needed for total items. Invalid or
// empty inputs have no pages.
func PageCount(total, perPage int) int {
	if total <= 0 || perPage <= 0 {
		return 0
	}
	return 1 + (total-1)/perPage
}

// Offset returns the zero-based offset for a one-based page. The second
// result is false when the inputs are invalid or the offset would overflow.
func Offset(page, perPage int) (int, bool) {
	if page < 1 || perPage < 1 {
		return 0, false
	}
	pageIndex := page - 1
	if pageIndex > math.MaxInt/perPage {
		return 0, false
	}
	return pageIndex * perPage, true
}

// Bounds returns safe half-open slice bounds for the requested page. The
// third result is false when the inputs are invalid, overflow, or the page is
// beyond the available items.
func Bounds(total, page, perPage int) (int, int, bool) {
	if total < 0 {
		return 0, 0, false
	}
	start, ok := Offset(page, perPage)
	if !ok || start >= total {
		return 0, 0, false
	}
	remaining := total - start
	if perPage >= remaining {
		return start, total, true
	}
	return start, start + perPage, true
}
