const Trip = require('../models/travlr');

/**
 * Retrieves all trips from the database.
 * Supports optional sorting and pagination via query params.
 *
 * @param {object} options
 * @param {string} [options.sortBy='start']  - Field to sort by
 * @param {string} [options.order='asc']     - 'asc' or 'desc'
 * @param {number} [options.page=1]          - Page number (1-indexed)
 * @param {number} [options.limit=0]         - Results per page (0 = no limit)
 * @returns {Promise<Trip[]>}
 */
const getAllTrips = async ({ sortBy = 'start', order = 'asc', page = 1, limit = 0 } = {}) => {
  const sortOrder = order === 'desc' ? -1 : 1;
  const sortObj = { [sortBy]: sortOrder };

  let query = Trip.find({}).sort(sortObj);

  if (limit > 0) {
    const skip = (page - 1) * limit;
    query = query.skip(skip).limit(limit);
  }

  return query.exec();
};

/**
 * Finds a single trip by its trip code.
 *
 * @param {string} tripCode
 * @returns {Promise<Trip|null>}
 */
const getTripByCode = async (tripCode) => {
  return Trip.findOne({ code: tripCode }).exec();
};

/**
 * Creates a new trip document.
 *
 * @param {object} tripData - Fields matching the Trip schema
 * @returns {Promise<Trip>}
 */
const createTrip = async (tripData) => {
  return Trip.create(tripData);
};

/**
 * Updates an existing trip identified by trip code.
 *
 * @param {string} tripCode
 * @param {object} tripData - Fields to update
 * @returns {Promise<Trip|null>}
 */
const updateTrip = async (tripCode, tripData) => {
  return Trip.findOneAndUpdate(
    { code: tripCode },
    tripData,
    { new: true, runValidators: true }
  );
};

/**
 * Deletes a trip by its trip code.
 *
 * @param {string} tripCode
 * @returns {Promise<Trip|null>}
 */
const deleteTrip = async (tripCode) => {
  return Trip.findOneAndDelete({ code: tripCode });
};

module.exports = {
  getAllTrips,
  getTripByCode,
  createTrip,
  updateTrip,
  deleteTrip,
};
