"use strict";
//const JwtHelper = require('../../helpers/jwt.helper');
const models = require("../../core/models");

const extraMethods = {
  findUser: async (params, context) => {
    return await models.User.findOne({
      where: params,
      include: [
        {
          required: false,
          model: models.Entity,
          as: "Entity",
        },
      ],
    });
  },

  findUserByPhone: async (Phone) => {
    return await models.User.findOne({
      where: { phone: Phone },
    });
  },

  createUser: async (params, context) => {
    //        return models.sequelize.transaction(async transaction => {
    //const result = await models.User.create(params, { transaction });
    const result = await models.User.create(params);
    return result;
    //        });
  },

  findUserByRefreshToken: async (refreshToken) => {
    return await models.User.findOne({
      where: {
        refresh_token: refreshToken,
        state: "active",
      },
    });
  },

  updateUserRefreshToken: async (userId, newRefreshToken) => {
    return await models.User.update(
      { refresh_token: newRefreshToken },
      { where: { id: userId } }
    );
  },

  deleteRefreshToken: async (userId, refreshToken) => {
    return await models.User.update(
      { refresh_token: null },
      { where: { id: userId } }
    );
  },


  updateUser: async (userId, params, context) => {
    let result = await models.User.update(params, {
      where: { id: userId }
    });

    return await extraMethods.findUser({
      id: userId
    }
    );

  },


  deleteUser: async (userId, userEmail, userPhone) => {
    return await models.User.destroy({
      where: {
        id: userId,
        email: userEmail,
        phone: userPhone,
        level: 1,
      }
    });
  }
};

module.exports = {
  extraMethods,
};
