module.exports = {
    friendlyName: 'Register FCM token',

    inputs: {
        userId: { type: 'string', required: true },
        deviceId: { type: 'string', required: true },
        platform: { type: 'string', isIn: ['android', 'ios'], required: true },
        fcmToken: { type: 'string', required: true },
        appVersion: { type: 'string' },
        lang: { type: 'string' }
    },

    exits: {
        success: { responseType: 'ok' },
        forbidden: { responseType: 'forbidden' }
    },

    fn: async function (inputs, exits) {
        const { user } = this.req.token;
        if (!user || user.codeUser !== inputs.userId) {
            return exits.forbidden({ message: 'Token non autorisé pour cet utilisateur' });
        }

        const payload = {
            codeUser: inputs.userId,
            deviceId: inputs.deviceId,
            platform: inputs.platform,
            fcmToken: inputs.fcmToken,
            appVersion: inputs.appVersion || null,
            lang: inputs.lang || null,
            codeEcole: user.codeEcole || null,
            lastActiveAt: new Date()
        };

        const existing = await PushToken.findOne({ codeUser: inputs.userId, deviceId: inputs.deviceId });
        let saved;
        if (existing) {
            saved = await PushToken.updateOne({ id: existing.id }).set(payload);
        } else {
            saved = await PushToken.create(payload).fetch();
        }

        return exits.success({ ok: true, tokenId: saved.id, updatedAt: saved.updatedAt || new Date() });
    }
};


