'use strict';

const express = require('express');
const router = express.Router();
const svc = require('../services/liveNotificationService');

function ok(res, data) { res.json({ ok: true, data }); }
function fail(res, message, code = 400) { res.status(code).json({ ok: false, error: message }); }

router.get('/status', (req, res) => ok(res, svc.status(req.query && req.query.deviceId)));

router.post('/subscribe', (req, res) => {
  try {
    const subscription = req.body && req.body.subscription;
    const meta = {
      userId: req.user && req.user.idusuario,
      deviceId: req.body && req.body.deviceId,
      endpoint: req.body && req.body.endpoint,
      userAgent: (req.body && req.body.userAgent) || req.headers['user-agent'] || '',
      platform: req.body && req.body.platform,
      deviceName: req.body && req.body.deviceName,
    };
    ok(res, svc.subscribe(subscription, meta));
  } catch (err) {
    fail(res, err.message || 'No se pudo guardar la suscripción');
  }
});

router.post('/unsubscribe', (req, res) => {
  try {
    ok(res, svc.unsubscribe(req.body && req.body.endpoint, req.body && req.body.deviceId));
  } catch (err) {
    fail(res, err.message || 'No se pudo quitar la suscripción');
  }
});

router.post('/test', async (req, res, next) => {
  try {
    const n = await svc.notify({
      type: 'sistema',
      title: 'Prueba de notificación',
      body: 'Las notificaciones en vivo están funcionando en este dispositivo.',
      url: '/',
      priority: 'normal',
    });
    ok(res, n);
  } catch (err) { next(err); }
});

module.exports = router;
