// src/routes/push.routes.js
const express = require('express');
const { body } = require('express-validator');

const verifyToken = require('../middleware/auth');
const handleValidation = require('../middleware/validate');
const config = require('../config');

const pushHttpService = require('../services/pushHttp.service');
const { sendPushToUser } = require('../services/push.service');

const router = express.Router();
router.use(verifyToken);

// GET /api/push/vapid-public-key
router.get('/vapid-public-key', (req, res) => {
  if (!config.vapid.publicKey) {
    return res.status(503).json({ success: false, message: 'Push indisponível' });
  }
  res.json({ success: true, data: { key: config.vapid.publicKey } });
});

// POST /api/push/subscribe
router.post(
  '/subscribe',
  [
    body('endpoint').isString(),
    body('keys.p256dh').isString(),
    body('keys.auth').isString(),
  ],
  handleValidation,
  async (req, res, next) => {
    try {
      const userId = req.user.id;
      const { endpoint, keys } = req.body;
      const ua = req.headers['user-agent'] || null;

      const out = await pushHttpService.subscribe(userId, endpoint, keys, ua);
      res.status(out.created ? 201 : 200).json({ success: true, data: out.row });
    } catch (err) {
      next(err);
    }
  }
);

// POST /api/push/unsubscribe
router.post(
  '/unsubscribe',
  [body('endpoint').optional().isString()],
  handleValidation,
  async (req, res, next) => {
    try {
      const userId = req.user.id;
      const { endpoint } = req.body || {};
      const out = await pushHttpService.unsubscribe(userId, endpoint);
      res.json({ success: true, message: out.message });
    } catch (err) {
      next(err);
    }
  }
);

// POST /api/push/test
router.post('/test', async (req, res, next) => {
  try {
    const userId = req.user.id;
    await sendPushToUser(userId, {
      title: '📬 Teste EV Station',
      body: 'Push notifications estão a funcionar!',
      url: '/',
    });
    res.json({ success: true, message: 'Push enviado' });
  } catch (err) {
    next(err);
  }
});

module.exports = router;
