import GameList, {GameListAttributes} from '../../db/models/GameList';
import {Op, fn, col, where, Order} from 'sequelize';

export const getAllGameListsRpo = async (filters: {
  name?: string;
  pagination?: boolean;
  page?: number;
  limit?: number;
}) => {
  const whereClause: any = {};

  if (filters.name) {
    whereClause.name = where(fn('LOWER', col('name')), {
      [Op.like]: `%${filters.name.toLowerCase()}%`,
    });
  }else{
    filters.limit=5
  }

  const order: Order = [['id', 'DESC']];

  if (filters.pagination) {
    const offset = (filters.page - 1) * filters.limit;
    const {rows, count} = await GameList.findAndCountAll({
      where: whereClause,
      order,
      limit: filters.limit,
      offset,
    });
    return {rows: rows.map((g) => g.toJSON()), count};
  } else {
    const rows = await GameList.findAll({
      attributes: ['id','name'],
      where: whereClause,
      order,
      limit: filters.limit,
    });
    return {rows: rows.map((g) => g.toJSON()), count: rows.length};
  }
};

export const getGameListByIdsRpo = async (id: number) => {
  return GameList.findByPk(id);
};