const express = require('express');
const authService = require('../services/auth.service');
const deviceService = require('../services/device.service');
const { requireAuth } = require('../middleware/auth');

const router = express.Router();

router.use(requireAuth);

router.get('/me', async (req, res, next) => {
  try {
    res.json(await authService.getProfile(req.user.id));
  } catch (err) {
    next(err);
  }
});

router.get('/vehicles', async (req, res, next) => {
  try {
    res.json(await deviceService.listVehicles(req.user.id));
  } catch (err) {
    next(err);
  }
});

router.post('/devices/activate', async (req, res, next) => {
  try {
    res.json(await deviceService.activateDevice(req.user.id, req.body || {}));
  } catch (err) {
    next(err);
  }
});

router.get('/devices/:id/live', async (req, res, next) => {
  try {
    res.json(await deviceService.getLive(req.user.id, Number(req.params.id)));
  } catch (err) {
    next(err);
  }
});

router.get('/devices/:id/history', async (req, res, next) => {
  try {
    res.json(
      await deviceService.getHistory(
        req.user.id,
        Number(req.params.id),
        req.query.from,
        req.query.to,
      ),
    );
  } catch (err) {
    next(err);
  }
});

router.get('/devices/:id/geofences', async (req, res, next) => {
  try {
    res.json(await deviceService.listGeofences(req.user.id, Number(req.params.id)));
  } catch (err) {
    next(err);
  }
});

router.post('/devices/:id/geofences', async (req, res, next) => {
  try {
    res.json(
      await deviceService.createGeofence(req.user.id, Number(req.params.id), req.body || {}),
    );
  } catch (err) {
    next(err);
  }
});

router.post('/devices/:id/position-lock', async (req, res, next) => {
  try {
    res.json(
      await deviceService.setPositionLock(req.user.id, Number(req.params.id), req.body || {}),
    );
  } catch (err) {
    next(err);
  }
});

router.get('/devices/:id/alerts', async (req, res, next) => {
  try {
    res.json(await deviceService.listAlerts(req.user.id, Number(req.params.id)));
  } catch (err) {
    next(err);
  }
});

router.post('/devices/:id/share', async (req, res, next) => {
  try {
    res.json(
      await deviceService.shareDevice(req.user.id, Number(req.params.id), req.body?.mobile),
    );
  } catch (err) {
    next(err);
  }
});

router.post('/devices/:id/transfer', async (req, res, next) => {
  try {
    res.json(await deviceService.createTransfer(req.user.id, Number(req.params.id)));
  } catch (err) {
    next(err);
  }
});

router.post('/devices/claim-transfer', async (req, res, next) => {
  try {
    res.json(await deviceService.claimTransfer(req.user.id, req.body?.transfer_token));
  } catch (err) {
    next(err);
  }
});

module.exports = router;
