/**
 * Pagination helper for list endpoints.
 * Only paginates when ?page= or ?limit= query params are present (backward compat).
 *
 * Usage:
 *   const { paginate, parsePaginationParams } = require('./pagination');
 *   router.get('/items', asyncHandler(async (req, res) => {
 *     const items = await getAllItems();
 *     const params = parsePaginationParams(req.query);
 *     res.json({ success: true, ...paginate(items, params) });
 *   }));
 */

const DEFAULT_LIMIT = 50;
const MAX_LIMIT = 200;

/**
 * Parse pagination params from query string.
 * Returns null if no pagination requested (backward compat: return full list).
 */
function parsePaginationParams(query) {
  if (!query.page && !query.limit) return null;
  const page = Math.max(1, parseInt(query.page, 10) || 1);
  const limit = Math.min(MAX_LIMIT, Math.max(1, parseInt(query.limit, 10) || DEFAULT_LIMIT));
  return { page, limit };
}

/**
 * Paginate an array of items.
 * If params is null, returns { data: items } (no pagination metadata).
 */
function paginate(items, params) {
  if (!params) return { data: items };

  const { page, limit } = params;
  const total = items.length;
  const totalPages = Math.ceil(total / limit);
  const start = (page - 1) * limit;
  const data = items.slice(start, start + limit);

  return {
    data,
    pagination: {
      page,
      limit,
      total,
      totalPages,
      hasMore: page < totalPages,
    },
  };
}

module.exports = { paginate, parsePaginationParams, DEFAULT_LIMIT, MAX_LIMIT };
