let moment = require('moment');

module.exports = {
  friendlyName: 'Login with Verification Code',
  description: 'First login with verification code and password setup',

  inputs: {
    username: {
      type: 'string',
      required: true
    },
    password: {
      type: 'string',
      required: true
    },
    codeVerif: {
      type: 'string',
      required: true
    },
    // Paramètres FCM optionnels
    fcmToken: {
      type: 'string',
      allowNull: true
    },
    deviceId: {
      type: 'string',
      allowNull: true
    },
    platform: {
      type: 'string',
      isIn: ['android', 'ios'],
      allowNull: true
    },
    appVersion: {
      type: 'string',
      allowNull: true
    },
    lang: {
      type: 'string',
      allowNull: true
    }
  },

  exits: {
    success: {
    },
    invalidInput: {

      description: 'Invalid input data'
    },
    userNotFound: {

      description: 'User not found or invalid code'
    },
    serverError: {

      description: 'Server error occurred'
    }
  },

  fn: async function ({ username, password, codeVerif, fcmToken, deviceId, platform, appVersion, lang }, exits) {
    //console.log('TEST 1 code', username, password, codeVerif)
    const ouestDate = moment.utc(new Date()).utcOffset('+01:00');
    const date = ouestDate.format('YYYY-MM-DD');
    const heure = ouestDate.format('HH:mm:ss');
    try {
      // 1. Validation des entrées
      if (!username || !password || !codeVerif) {
        await ActivityLogs.create({
          date,
          heure,
          username,
          action: "CONNEXION_CODEVERIF_MOBILE",
          status: "failed",
          errorMessage: "Tous les champs sont obligatoires",
          device: "Mobile"
        });
        return exits.invalidInput({
          success: false,
          message: 'Tous les champs sont obligatoires',
          code: 'MISSING_FIELDS'
        });
      }

      // 2. Chiffrement du mot de passe
      let encryptedPassword;
      try {
        encryptedPassword = await new Promise((resolve, reject) => {
          sails.config.cryptoUtils.encrypt(password, (err, result) => {
            if (err) reject(err);
            else resolve(result);
          });
        });
      } catch (encryptError) {
        await ActivityLogs.create({
          date,
          heure,
          username,
          action: "CONNEXION_CODEVERIF_MOBILE",
          status: "failed",
          errorMessage: "Erreur de chiffrement",
          device: "Mobile"
        });
        return exits.serverError({
          success: false,
          message: 'Erreur de chiffrement',
          code: 'ENCRYPTION_ERROR'
        });
      }

      // 3. Recherche de l'utilisateur
      const user = await Utilisateurs.findOne({
        login: username.toLowerCase().trim(),
        codeVerif: codeVerif,
        desactiverCompte: false
      });

      if (!user) {
        await ActivityLogs.create({
          date,
          heure,
          username,
          action: "CONNEXION_CODEVERIF_MOBILE",
          status: "failed",
          errorMessage: "Utilisateur non trouvé ou code invalide",
          device: "Mobile"
        });
        return exits.userNotFound({
          success: false,
          message: 'Utilisateur non trouvé ou code invalide',
          code: 'INVALID_CREDENTIALS'
        });
      }

      // 4. Mise à jour du mot de passe
      await Utilisateurs.updateOne({ id: user.id })
        .set({
          password: encryptedPassword,
          isUpdate: true
        });

      // 5. Génération du token JWT
      const token = await sails.helpers.jwt.sign.with({ payload: user });
      if (!token) {
        await ActivityLogs.create({
          date,
          heure,
          username,
          action: "CONNEXION_CODEVERIF_MOBILE",
          status: "failed",
          errorMessage: "Token non généré",
          device: "Mobile"
        });
        throw new Error('Token generation failed');
      }

      // 6. Enregistrement du token
      await Token.create({
        token_salt: token,
        owner: user.id
      });

      // 7. Récupération des infos école
      const ecole = await Ecoles.findOne({ codeEcole: user.codeEcole });

      // 8. Enregistrement du token FCM (si fourni)
      if (fcmToken && deviceId && platform) {
        try {
          // Utiliser le helper upsert-fcm-token
          await sails.helpers.upsertFcmToken.with({
            codeUser: user.codeUser,
            deviceId: deviceId,
            platform: platform,
            fcmToken: fcmToken,
            codeEcole: user.codeEcole,
            appVersion: appVersion || '1.0.0',
            lang: lang || 'fr'
          });

          sails.log.info(`FCM token registered for user ${user.codeUser} on ${platform}`);
        } catch (fcmError) {
          sails.log.warn(`Failed to register FCM token for user ${user.codeUser}:`, fcmError.message);
          // On ne fait pas échouer la connexion si FCM échoue
        }
      }

      // 9. Journalisation (succès)
      await ActivityLogs.create({
        date,
        heure,
        username: user.login,
        action: "CONNEXION_CODEVERIF_MOBILE",
        status: "success",
        errorMessage: null,
        device: "Mobile"
      });

      // 9. Préparation de la réponse
      const response = {
        success: true,
        message: 'Connexion réussie',
        token: token,
        user: {
          id: user.id,
          login: user.login,
          email: user.email,
          firstName: user.prenom,
          lastName: user.nom,
          isUpdate: true,
          typeUser: user.typeUser
        },
        school: ecole ? {
          id: ecole.id,
          name: ecole.nom,
          code: ecole.codeEcole
        } : null
      };
      console.log('TEST 8 code', response)

      return exits.success(response);

    } catch (error) {
      sails.log.error('Login error:', error);
      await ActivityLogs.create({
        date,
        heure,
        username,
        action: "CONNEXION_CODEVERIF_MOBILE",
        status: "failed",
        errorMessage: (error && error.message) || 'Erreur inconnue',
        device: "Mobile"
      });
      return exits.serverError({
        success: false,
        message: 'Une erreur est survenue',
        code: 'SERVER_ERROR',
        details: error.message
      });
    }
  }
};