// src/routes/sessions.routes.js
const express = require('express');
const { param, query, body } = require('express-validator');

const verifyToken = require('../middleware/auth');
const handleValidation = require('../middleware/validate');
const sessionsService = require('../services/sessions.service');

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

// GET /api/charger_sessions?chargerId=...
router.get(
  '/',
  [query('chargerId').isUUID().withMessage('chargerId deve ser UUID válido')],
  handleValidation,
  async (req, res, next) => {
    try {
      const { chargerId } = req.query;
      const data = await sessionsService.listByCharger(req.user.id, chargerId);
      res.json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }
);

// ✅ /history antes de /:id
router.get(
  '/history/:chargerId',
  [
    param('chargerId').isUUID().withMessage('chargerId deve ser UUID válido'),
    query('viewMode').isIn(['Day', 'Week', 'Month']).withMessage('viewMode inválido'),
  ],
  handleValidation,
  async (req, res, next) => {
    try {
      const { chargerId } = req.params;
      const { viewMode } = req.query;

      const data = await sessionsService.history(req.user.id, chargerId, viewMode);
      res.json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }
);

router.get(
  '/:id',
  [param('id').isInt().withMessage('ID de sessão inválido')],
  handleValidation,
  async (req, res, next) => {
    try {
      const data = await sessionsService.getById(req.user.id, Number(req.params.id));
      res.json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }
);

router.post(
  '/',
  [body('charger_id').isUUID().withMessage('charger_id deve ser UUID válido')],
  handleValidation,
  async (req, res, next) => {
    try {
      const data = await sessionsService.create(req.user.id, req.body.charger_id);
      res.status(201).json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }
);

router.put(
  '/:id',
  [
    param('id').isInt().withMessage('ID de sessão inválido'),
    body('ended_at').optional().isISO8601().toDate(),
    body('kwh').optional().isFloat({ min: 0 }),
    body('cost').optional().isFloat({ min: 0 }),
  ],
  handleValidation,
  async (req, res, next) => {
    try {
      const id = Number(req.params.id);
      const { ended_at, kwh, cost } = req.body;

      const data = await sessionsService.update(req.user.id, id, { ended_at, kwh, cost });
      res.json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }
);

router.delete(
  '/:id',
  [param('id').isInt().withMessage('ID de sessão inválido')],
  handleValidation,
  async (req, res, next) => {
    try {
      const ok = await sessionsService.remove(req.user.id, Number(req.params.id));
      res.json({ success: true, message: ok ? 'Sessão excluída com sucesso' : 'OK' });
    } catch (err) {
      next(err);
    }
  }
);

module.exports = router;
