/**
 * manage-fcm-topic
 *
 * Abonne/désabonne un token FCM à un topic via Instance ID API
 */

module.exports = {
    friendlyName: 'Gérer abonnement topic FCM',

    inputs: {
        fcmToken: { type: 'string', required: true },
        topic: { type: 'string', required: true },
        action: { type: 'string', isIn: ['subscribe', 'unsubscribe'], required: true }
    },

    exits: {
        success: { description: 'OK' },
        error: { description: 'Erreur' }
    },

    fn: async function (inputs, exits) {
        try {
            // Utiliser la configuration Firebase centralisée
            const firebaseConfig = sails.config.firebase;
            const serverKey = firebaseConfig.serverKey;

            if (!serverKey) {
                throw new Error('FIREBASE_SERVER_KEY manquant pour gestion des topics');
            }

            const axios = require('axios');
            const url = `${firebaseConfig.fcm.iidApiUrl}/${encodeURIComponent(inputs.fcmToken)}/rel/topics/${encodeURIComponent(inputs.topic)}`;
            const headers = {
                'Authorization': `key=${serverKey}`,
                'Content-Type': 'application/json'
            };

            // Subscribe au topic
            if (inputs.action === 'subscribe') {
                const resp = await axios.post(url, {}, {
                    headers,
                    timeout: firebaseConfig.fcm.timeout
                });
                sails.log.info(`✅ Token FCM ${inputs.fcmToken.substring(0, 10)}... abonné au topic ${inputs.topic}`);
                return exits.success(resp.data || { ok: true });
            }

            // Unsubscribe du topic via batchRemove
            const batchUrl = `${firebaseConfig.fcm.iidApiUrl}:batchRemove`;
            const payload = {
                to: `/topics/${inputs.topic}`,
                registration_tokens: [inputs.fcmToken]
            };

            const resp = await axios.post(batchUrl, payload, {
                headers,
                timeout: firebaseConfig.fcm.timeout
            });

            sails.log.info(`✅ Token FCM ${inputs.fcmToken.substring(0, 10)}... désabonné du topic ${inputs.topic}`);
            return exits.success(resp.data || { ok: true });

        } catch (e) {
            sails.log.warn('FCM topic action failed:', e.response?.data || e.message);
            return exits.error(e);
        }
    }
};


