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 tripsQueryController = require('../controllers/tripsQuery');
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

// Enhancement Two (algorithms and data structures) endpoints. These
// MUST be registered before /trips/:tripCode, or Express would match
// "search" and "recommendations" as trip codes.
router
    .route('/trips/search')
    .get(tripsQueryController.tripsSearch);           // public, read-only

router
    .route('/trips/recommendations')
    .get(tripsQueryController.tripsRecommendations);  // public, read-only

// 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;
