import { Op, Sequelize } from "sequelize";
import { searchScheduleCache } from "../../helpers/SchedulingNotifyCache";
import SchedulingNotify from "../../models/SchedulingNotify";

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

interface Response {
  schedulingNotifies: SchedulingNotify[];
  count: number;
  hasMore: boolean;
}

const ListSchedulingNotifyService = async ({
  searchParam = "",
  pageNumber = "1"
}: Request): Promise<Response> => {
  // const whereCondition = {
  //   message: Sequelize.where( 

  //      Sequelize.fn("date", Sequelize.col("schedulingDate")), `${searchParam.toLowerCase().trim()}`,

  //      ),

  // };

  let date = searchParam.split(' ')[0]
  let hour = searchParam.split(' ')[1].split(':')[0]
  let minute = searchParam.split(' ')[1].split(':')[1]

  let fromCache = null

  fromCache = await searchScheduleCache(date, hour, minute)

  if (fromCache) {

    return {
      schedulingNotifies: fromCache,
      count: 0,
      hasMore: false,
    };

  }


  const whereCondition = {
    [Op.and]: [
      {
        "$schedulingTime$": Sequelize.where(Sequelize.fn("date", Sequelize.col("schedulingTime")), `${date.trim()}`)
      },
      {
        "$schedulingTime$": Sequelize.where(Sequelize.fn("hour", Sequelize.col("schedulingTime")), `${hour.trim()}`)
      },
      {
        "$schedulingTime$": Sequelize.where(Sequelize.fn("minute", Sequelize.col("schedulingTime")), `${minute.trim()}`)
      }
    ]
  };


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

  const { count, rows: schedulingNotifies } = await SchedulingNotify.findAndCountAll({
    raw: true,
    where: whereCondition,
    limit,
    offset,
    order: [["id", "ASC"]]
  });

  const hasMore = count > offset + schedulingNotifies.length;

  return {
    schedulingNotifies,
    count,
    hasMore
  };
};

export default ListSchedulingNotifyService;
