import { Op, Sequelize } from "sequelize"; 
import Position from "../../models/Position";

interface Request {
  searchParam?: string;
  pageNumber?: string;
}

interface Response {
  positions: Position[];
  count: number;
  hasMore: boolean;
}

const ListPositionService = async ({
  searchParam = "",
  pageNumber = "1"
}: Request): Promise<Response> => {
  console.log("searchParam: ", searchParam);

  const whereCondition = {
    message: Sequelize.where(
      Sequelize.fn("LOWER", Sequelize.col("name")),
      "LIKE",
      `%${searchParam.toLowerCase().trim()}%`
    )
  };

  const limit = 20;
  const offset = limit * (+pageNumber - 1);

  let { count, rows: positions } = await Position.findAndCountAll({
    where: whereCondition,
    limit,
    offset,
    order: [["name", "ASC"]]
  });

  const hasMore = count > offset + positions.length;

  return {
    positions,
    count,
    hasMore
  };
};

export default ListPositionService;
