/**
 * Pagination middleware for list endpoints
 * Parses page and limit query parameters and adds pagination helpers to req object
 */
const paginate = (req, res, next) => {
  // Parse page and limit from query params
  const page = parseInt(req.query.page) || 1;
  const limit = Math.min(parseInt(req.query.limit) || 10, 100); // Max 100 items per page

  // Validate page and limit
  if (page < 1) {
    return res.status(400).json({ msg: "Page must be greater than 0" });
  }

  if (limit < 1) {
    return res.status(400).json({ msg: "Limit must be greater than 0" });
  }

  // Calculate skip value for MongoDB
  const skip = (page - 1) * limit;

  // Attach pagination data to request
  req.pagination = {
    page,
    limit,
    skip,
  };

  next();
};

/**
 * Helper function to build paginated response
 * @param {Array} data - Array of documents
 * @param {number} totalCount - Total number of documents
 * @param {number} page - Current page number
 * @param {number} limit - Items per page
 * @returns {Object} Paginated response object
 */
const buildPaginatedResponse = (data, totalCount, page, limit) => {
  const totalPages = Math.ceil(totalCount / limit);

  return {
    data,
    pagination: {
      currentPage: page,
      totalPages,
      totalCount,
      itemsPerPage: limit,
      hasNextPage: page < totalPages,
      hasPrevPage: page > 1,
    },
  };
};

module.exports = {
  paginate,
  buildPaginatedResponse,
};
