# app/services/concerns/paginatable.rb
module Paginatable
  extend ActiveSupport::Concern
  include ServiceResponse

  included do
    # Adds pagination logic that can be reused
    def paginate(query, page: 1, per_page: 10)
      # Ensure page and per_page are positive integers
      page = [page.to_i, 1].max  # Ensure page is at least 1
      per_page = [per_page.to_i, 1].max  # Ensure per_page is at least 1

      total_count = query.count
      total_pages = (total_count.to_f / per_page).ceil

      # Adjust page if it exceeds total pages
      page = [page, total_pages].min unless total_pages.zero?

      # Calculate skip value (will always be >= 0 since page and per_page are positive)
      skip = (page - 1) * per_page

      records = query.skip(skip).limit(per_page)

      # Calculate next and previous pages
      prev_page = page > 1 ? page - 1 : nil
      next_page = page < total_pages ? page + 1 : nil

      options = {
        total_pages: total_pages,
        total_count: total_count,
        current_page: page,
        per_page: per_page,
        prev_page: prev_page,
        next_page: next_page
      }

      success_response(
        data: records,
        options: options
      )
    end
  end
end 