/* global User */
"use strict";

const _ = require("lodash");
const moment = require("moment");
const { generateService, parseParamsToFindOptions } = require("../../helpers/service.helper");
const models = require("../../core/models");
const Sequelize = require("sequelize");
moment.locale("es");

const extraMethods = {
  _getUserByEmail: async (email) => {
    return models.User.findOne({
      where: {
        email: email,
      },
    });
  },

  _getUserById: async (Id) => {
    return models.User.findOne({
      where: {
        id: Id,
      },
    });
  },

  _getActiveUserIds: async (offset = 0, limit = 10, country = "ES") => {
    return models.User.findAndCountAll({
      attributes: ["id"],
      where: {
        state: "active",
        phone: { [Sequelize.Op.ne]: null },
        country: country === "*" ? { [Sequelize.Op.ne]: null } : country,
      },
      raw: true,
      limit: limit,
      offset: offset,
    });
  },

  _updateLastLoginAndVersionUser: async (id, appVersion) => {
    return models.User.update(
      {
        app_version: appVersion,
        lastlogin: moment().utc(),
      },
      {
        where: { id: id },
      }
    );
  },

  //solo se llama desde APP
  _getOrCreateUser: async (dataUser) => {
    let result = null;
    //console.log('_getOrCreateUser>>>>>>><');

    if (dataUser.userResult) {
      result = { user: dataUser.userResult, isCreated: false };
    } else {
      await models.User.findOrCreate({
        where: {
          phone: dataUser.phone ? dataUser.phone : null, //puede que al venir la solicitud por web no venga el phone
          email: dataUser.email,
        },
        include: [{ model: models.Entity }],
        defaults: {
          phone: dataUser.phone,
          email: dataUser.email,
          name: dataUser.name,
          surname: dataUser.surname,
          entityId: dataUser.entityId,
          profile: dataUser.profile,
          //                        password: crypto.createHash('sha512').update(user.phone).digest('hex'),
        },
      }).then(([user, created]) => {
        user = user.toJSON();
        result = { user: user, isCreated: created };
      });
    }
    return result;
  },

  //solo se llama desde formualario WEB
  _getOrCreateUserWEB: async (dataUser) => {
    let result = null;
    console.log('_getOrCreateUserWEB>>>>>>><');

    if (dataUser.userResult) {
      result = { user: dataUser.userResult, isCreated: false };
    } else {
      await models.User.findOrCreate({
        where: {
          phone: dataUser.phone ? dataUser.phone : null, //puede que al venir la solicitud por web no venga el phone
          email: dataUser.email,
          name: dataUser.name,
          surname: dataUser.surname,
        },
        include: [{ model: models.Entity }],
        defaults: {
          phone: dataUser.phone,
          email: dataUser.email,
          name: dataUser.name,
          surname: dataUser.surname,
          entityId: dataUser.entityId,
          profile: "guest",
          //                        password: crypto.createHash('sha512').update(user.phone).digest('hex'),
        },
      }).then(([user, created]) => {
        user = user.toJSON();
        result = { user: user, isCreated: created };
      });
    }
    return result;
  },

  //solo se llama desde formualario WEB nuevo
  _getOrCreateUserWEBV4: async (dataUser, req) => {
    let result = null;
    dataUser = {
      name: req.body.name ? req.body.name : null,
      surname: req.body.surname ? req.body.surname : null,
      email: req.body.email ? req.body.email : null,
      profile: req.body.profile ? req.body.profile : 'guest',
      country: req.body.country ? req.body.country : 'ES',
      entityId: dataUser.entityId ? dataUser.entityId : req.body.entityId,
      //entityName: null,
      //entityLevel: null,
      userResult: null,
    };
//    console.log('_getOrCreateUserWEBV4>22222222>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', dataUser);

    if (dataUser.userResult) {
      result = { user: dataUser.userResult, isCreated: false };
    } else {
      await models.User.findOrCreate({
        where: {
          email: dataUser.email,
          name: dataUser.name,
          surname: dataUser.surname,
        },
//        include: [{ model: models.Entity }],  //lo quitamos porque el join con entidad vacia nunca lo encuentra y siempre crea el correo.
        defaults: {
          email: dataUser.email,
          name: dataUser.name,
          surname: dataUser.surname,
          profile: dataUser.profile,
          country: dataUser.country,
          entityId: dataUser.entityId,
          //                        password: crypto.createHash('sha512').update(user.phone).digest('hex'),
        },
      }).then(([user, created]) => {
        user = user.toJSON();
        result = { user: user, isCreated: created };
      });
    }
    return result;
  },

};

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