module.exports = {


  friendlyName: 'Modify',


  description: 'Modify password.',


  inputs: {
    oldPassword: {
      type: 'string',
      required: true
    },
    newPassword: {
      type: 'string',
      required: true
    }
  },


  exits: {
    notFound: {
      statusCode: 404
    },
    encryptionError: {
      statusCode: 500
    }
  },


  fn: async function ({ oldPassword, newPassword }, exits) {
    const { id } = this.req.token
    const login = this.req.token.user.login
    const momentNow = require('moment').utc(new Date()).utcOffset('+01:00');
    const date = momentNow.format('YYYY-MM-DD');
    const heure = momentNow.format('HH:mm:ss');
    try {
      let user = await Utilisateurs.find({ login: login, codeVerif: oldPassword }).then(_.first)
      if (!user) {
        await ActivityLogs.create({
          date,
          heure,
          username: login,
          action: "RESET_PASSWORD",
          status: "failed",
          errorMessage: "User not found",
          device: "Web"
        });
        throw { notFound: { message: "User not found" } }
      }
      await Utilisateurs.update({ login: login }, { codeVerif: newPassword })
      await ActivityLogs.create({
        date,
        heure,
        username: login,
        action: "RESET_PASSWORD",
        status: "success",
        errorMessage: null,
        device: "Web"
      });
      return exits.success({ Done: true })
    } catch (err) {
      await ActivityLogs.create({
        date,
        heure,
        username: login,
        action: "RESET_PASSWORD",
        status: "failed",
        errorMessage: (typeof err === 'string' ? err : (err && err.message) || 'Erreur inconnue'),
        device: "Web"
      });
      throw err;
    }
  }

};
