const express = require('express');
const router = express.Router();

// Controllers and middleware. authenticateJWT was extracted from this
// file into app_api/middleware for separation of concerns; the
// centralized error handlers guarantee JSON responses for all /api
// failures.
const tripsController = require('../controllers/trips');
const authController = require('../controllers/authentication');
const authenticateJWT = require('../middleware/authenticateJWT');
const { notFoundHandler, errorHandler } = require('../middleware/errorHandler');

// define route for our trips endpoint
router
    .route('/trips')
    .get(tripsController.tripsList)                        // GET is public
    .post(authenticateJWT, tripsController.tripsAddTrip);  // POST requires JWT

// GET, PUT, DELETE routes for trips/:tripCode - requires parameter
// Code review finding: DELETE previously had no authentication, so any
// anonymous client could remove records. It is now JWT protected like
// the other mutating routes.
router
    .route('/trips/:tripCode')
    .get(tripsController.tripsFindByCode)                          // GET is public
    .put(authenticateJWT, tripsController.tripsUpdateTrip)         // PUT requires JWT
    .delete(authenticateJWT, tripsController.tripsDeleteTrip);     // DELETE requires JWT

// define route for login endpoint
router
    .route('/login')
    .post(authController.login);

// define route for register endpoint
router
    .route('/register')
    .post(authController.register);

// Unknown /api paths return JSON 404s; all errors thrown or forwarded
// from the routes above converge on the centralized error handler.
router.use(notFoundHandler);
router.use(errorHandler);

module.exports = router;
