let moment = require('moment');

module.exports = {
  friendlyName: 'Flutter Login Verification',
  description: 'API spéciale pour la vérification de connexion depuis l\'app Flutter',

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

  exits: {
    success: {
      // Force le retour en JSON
    },
    invalid: {

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

      description: 'Utilisateur non trouvé'
    }
  },

  fn: async function ({ username }, 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 || username.trim() === '') {
        await ActivityLogs.create({
          date,
          heure,
          username,
          action: "VERIFY_USER_MOBILE",
          status: "failed",
          errorMessage: "Nom d'utilisateur requis",
          device: "Mobile"
        });
        return exits.invalid({
          success: false,
          message: 'Nom d\'utilisateur requis',
          code: 'INVALID_INPUT'
        });
      }
      let user;
      user = await Utilisateurs.findOne({
        login: username.toLowerCase().trim(),
        desactiverCompte: false
      });
      if (!user) {
        await ActivityLogs.create({
          date,
          heure,
          username,
          action: "VERIFY_USER_MOBILE",
          status: "failed",
          errorMessage: "Identifiant incorrect",
          device: "Mobile"
        });
        return exits.notFound({
          success: false,
          message: 'Identifiant incorrect',
          code: 'USER_NOT_FOUND',
          isFirstLogin: false
        });
      }
      await ActivityLogs.create({
        date,
        heure,
        username: user.login,
        action: "VERIFY_USER_MOBILE",
        status: "success",
        errorMessage: null,
        device: "Mobile"
      });
      return exits.success({
        success: true,
        isFirstLogin: !user.isUpdate,
        user: {
          id: user.id.toString(),
          login: user.login
        },
        message: user.isUpdate ? 'Compte déjà configuré' : 'Première connexion'
      });
    } catch (err) {
      await ActivityLogs.create({
        date,
        heure,
        username,
        action: "VERIFY_USER_MOBILE",
        status: "failed",
        errorMessage: (err && err.message) || 'Erreur inconnue',
        device: "Mobile"
      });
      return exits.error({
        success: false,
        message: 'Erreur serveur',
        code: 'SERVER_ERROR',
        isFirstLogin: false
      });
    }
  }
};