let moment = require('moment');

module.exports = {
  friendlyName: 'Flutter Code Verification',
  description: 'Vérification du code pour l\'application Flutter',

  inputs: {
    username: {
      type: 'string',
      required: true
    },
    code: {
      type: 'string',
      required: true
    }
  },

  exits: {
    success: {
    },
    invalid: {

      description: 'Données invalides'
    },
    notFound: {

      description: 'Code ou utilisateur incorrect'
    }
  },

  fn: async function ({ username, code }, exits) {
    const ouestDate = moment.utc(new Date()).utcOffset('+01:00');
    const date = ouestDate.format('YYYY-MM-DD');
    const heure = ouestDate.format('HH:mm:ss');
    try {
      if (!username || !code) {
        await ActivityLogs.create({
          date,
          heure,
          username,
          action: "VERIFY_CODEVERIF_MOBILE",
          status: "failed",
          errorMessage: "Nom d'utilisateur et code requis",
          device: "Mobile"
        });
        return exits.invalid({
          success: false,
          message: 'Nom d\'utilisateur et code requis',
          code: 'INVALID_INPUT'
        });
      }
      let user;
      user = await Utilisateurs.findOne({
        login: username.toLowerCase().trim(),
        codeVerif: code,
        desactiverCompte: false
      });
      if (!user) {
        await ActivityLogs.create({
          date,
          heure,
          username,
          action: "VERIFY_CODEVERIF_MOBILE",
          status: "failed",
          errorMessage: "Code de vérification incorrect",
          device: "Mobile"
        });
        return exits.notFound({
          success: false,
          message: 'Code de vérification incorrect',
          code: 'INVALID_CODE',
          isFirstLogin: false
        });
      }
      await ActivityLogs.create({
        date,
        heure,
        username: user.login,
        action: "VERIFY_CODEVERIF_MOBILE",
        status: "success",
        errorMessage: null,
        device: "Mobile"
      });
      return exits.success({
        success: true,
        isFirstLogin: !user.isUpdate,
        user: {
          id: user.id.toString(),
          login: user.login
        },
        message: 'Code valide'
      });
    } catch (err) {
      await ActivityLogs.create({
        date,
        heure,
        username,
        action: "VERIFY_CODEVERIF_MOBILE",
        status: "failed",
        errorMessage: (err && err.message) || 'Erreur inconnue',
        device: "Mobile"
      });
      return exits.error({
        success: false,
        message: 'Erreur serveur',
        code: 'SERVER_ERROR'
      });
    }
  }
};