/**
 * Generates pagination options for database queries
 * @param {Object} options - Pagination options
 * @param {number} options.page - Current page number
 * @param {number} options.limit - Number of items per page
 * @param {string} options.sortBy - Field to sort by
 * @param {string} options.sortOrder - Sort order ('asc' or 'desc')
 * @returns {Object} Pagination options object
 */
const getPagination = (options = {}) => {
  // Default values
  const page = options.page ? parseInt(options.page, 10) : 1;
  const limit = options.limit ? parseInt(options.limit, 10) : 10;
  const sortBy = options.sortBy || 'createdAt';
  const sortOrder = options.sortOrder === 'desc' ? -1 : 1;
  
  // Calculate skip value for pagination
  const skip = (page - 1) * limit;
  
  // Create sort object
  const sort = {};
  sort[sortBy] = sortOrder;
  
  return {
    page,
    limit,
    skip,
    sort,
    sortBy,
    sortOrder: sortOrder === -1 ? 'desc' : 'asc'
  };
};

/**
 * Get pagination data for a model with count and pagination info
 * @param {Object} model - The Mongoose model or BaseModel instance
 * @param {number} page - Page number
 * @param {number} limit - Items per page
 * @param {Object} query - Query object for filtering
 * @returns {Object} Object with skip, limit, and pagination info
 */
const getModelPagination = async (model, page = 1, limit = 10, query = {}) => {
  page = parseInt(page, 10);
  limit = parseInt(limit, 10);
  const skip = (page - 1) * limit;
  
  // Get total count of documents matching the query
  const total = await model.countDocuments(query);
  const totalPages = Math.ceil(total / limit);
  
  return {
    skip,
    limit,
    pagination: {
      total,
      totalPages,
      currentPage: page,
      hasNextPage: page < totalPages,
      hasPreviousPage: page > 1
    }
  };
};

/**
 * Generates pagination metadata
 * @param {number} total - Total number of items
 * @param {number} page - Current page number
 * @param {number} limit - Number of items per page
 * @returns {Object} Pagination metadata
 */
const getPagingData = (total, page, limit) => {
  const currentPage = page ? +page : 1;
  const totalPages = Math.ceil(total / limit);
  const hasNextPage = currentPage < totalPages;
  const hasPreviousPage = currentPage > 1;
  
  return {
    total,
    totalPages,
    currentPage,
    itemsPerPage: limit,
    hasNextPage,
    hasPreviousPage,
    nextPage: hasNextPage ? currentPage + 1 : null,
    previousPage: hasPreviousPage ? currentPage - 1 : null
  };
};

module.exports = {
  getPagination,
  getPagingData,
  getModelPagination
};
