const { Op } = require("sequelize");

class PaginationService {
  /**
   * Handle offset-based pagination with sorting
   */
  static async paginateWithSort(model, options = {}) {
    const {
      page = 1,
      limit = 10,
      sort = "id",
      direction = "ASC",
      where = {},
    } = options;

    const offset = (page - 1) * limit;
    const order = [[sort, direction.toUpperCase()]];

    const { count, rows } = await model.findAndCountAll({
      where,
      order,
      limit: parseInt(limit),
      offset: parseInt(offset),
    });

    const totalPages = Math.ceil(count / limit);

    return {
      total: count,
      page: parseInt(page),
      totalPages,
      list: rows,
    };
  }

  /**
   * Handle cursor-based pagination
   */
  static async paginateWithCursor(model, options = {}) {
    const {
      id,
      limit = 10,
      sort = "id",
      direction = "ASC",
      where = {},
    } = options;

    const order = [[sort, direction.toUpperCase()]];
    const cursorWhere = {
      ...where,
      [sort]: {
        [direction.toUpperCase() === "ASC" ? Op.gt : Op.lt]: id,
      },
    };

    const rows = await model.findAll({
      where: cursorWhere,
      order,
      limit: parseInt(limit),
    });

    return {
      id: parseInt(id),
      list: rows,
    };
  }

  /**
   * Get odd order IDs
   */
  static async getOddOrders(model) {
    return await model.findAll({
      where: {
        id: {
          [Op.mod]: [2, 1], // id % 2 = 1 (odd numbers)
        },
      },
    });
  }
}

module.exports = PaginationService;
