const moment = require("moment");
const { Expo } = require("expo-server-sdk");
const { generateService, parseParamsToFindOptions } = require("../../helpers/service.helper");
const models = require("../../core/models");
const { Sequelize } = require("sequelize");

const extraMethods = {
  isValidPushToken: (token) => {
    return Expo.isExpoPushToken(token);
  },

  afterFetchAll: (result, params, context) => {
    if (!result.count) {
      return result;
    }

    let rows = result.rows.map((row) => row.toJSON());

    return {
      count: result.count,
      rows: rows,
    };
  },

  getPushToken: (params) => {
    return models.UserDevice.findOne({
      where: params,
    });
  },

  _getActiveDeviceIds: async (offset = 0, limit = 10, country = "ES") => {
    return models.UserDevice.findAndCountAll({
      where: {
        valid: 1,
        country: country === "*" ? { [Sequelize.Op.ne]: null } : country,
      },
      raw: true,
      limit: limit,
      offset: offset,
    });
  },
};

module.exports = generateService(models.UserDevice, extraMethods);
