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

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

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

router.get('/', async (req, res, next) => {
  try {
    const data = await chargersService.list(req.user.id);
    res.json({ success: true, data });
  } catch (err) {
    next(err);
  }
});

router.get(
  '/:id',
  [param('id').isUUID()],
  handleValidation,
  async (req, res, next) => {
    try {
      const data = await chargersService.getOne(req.user.id, req.params.id);
      res.json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }
);

router.post(
  '/',
  [body('location').exists().isString().isLength({ min: 1 }).trim()],
  handleValidation,
  async (req, res, next) => {
    try {
      const data = await chargersService.create(req.user.id, req.body.location);
      res.status(201).json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }
);

router.put(
  '/:id',
  [
    param('id').isUUID(),
    body('charger').optional().isObject(),
    body('config').optional().isObject(),
    body('location').optional().isString(),
  ],
  handleValidation,
  async (req, res, next) => {
    try {
      const data = await chargersService.update(req.user.id, req.params.id, req.body);
      res.json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }
);

router.delete(
  '/:id',
  [param('id').isUUID()],
  handleValidation,
  async (req, res, next) => {
    try {
      await chargersService.remove(req.user.id, req.params.id);
      res.json({ success: true, message: 'Carregador excluído com sucesso' });
    } catch (err) {
      next(err);
    }
  }
);

router.put(
  '/:id/config',
  [param('id').isUUID(), body('config').isObject()],
  handleValidation,
  async (req, res, next) => {
    try {
      const out = await chargersService.updateConfig(req.user.id, req.params.id, req.body.config);
      res.json({ success: true, data: out.data, message: out.message });
    } catch (err) {
      next(err);
    }
  }
);

router.get(
  '/:id/schedule',
  [param('id').isUUID()],
  handleValidation,
  async (req, res, next) => {
    try {
      const data = await chargersService.getSchedules(req.user.id, req.params.id);
      res.json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }
);

router.post(
  '/:id/schedule',
  [
    param('id').isUUID(),
    body('start').matches(/^\d{2}:\d{2}$/),
    body('end').matches(/^\d{2}:\d{2}$/),
    body('repeat').isIn(['everyday', 'weekdays', 'weekends']),
  ],
  handleValidation,
  async (req, res, next) => {
    try {
      const { start, end, repeat } = req.body;
      const data = await chargersService.createSchedule(req.user.id, req.params.id, start, end, repeat);
      res.status(201).json({ success: true, data });
    } catch (err) {
      next(err);
    }
  }
);

router.post(
  '/:id/action',
  [
    param('id').isUUID(),
    body('action').isIn(['start', 'stop']),
    body('ampLimit').optional().isInt({ min: 6, max: 64 }),
  ],
  handleValidation,
  async (req, res, next) => {
    try {
      const { action, ampLimit } = req.body;
      await chargersService.action(req.user.id, req.params.id, action, ampLimit);
      res.json({ success: true, message: `Comando '${action}' enviado com sucesso` });
    } catch (err) {
      next(err);
    }
  }
);

module.exports = router;
