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

/*const postService = require('./post.service')(models.Post);
const postController = require('./post.controller')(postService);*/
const { cacheSuccesses } = require('../../middlewares/cache');
const { isAdministratorUser, isLoggedUser } = require('../../middlewares/accessValidator');
const PaginateMiddleware = require('../../middlewares/paginate');
const SortMiddleware = require('../../middlewares/sort');
const FieldMiddleware = require('../../middlewares/fields');

const blogController = require('./blog.controller')

routes.get('/posts', isLoggedUser,
  cacheSuccesses('24 hours'),
  FieldMiddleware.middleware({
    invalidFields: ['user', 'createdAt']
  }),
  PaginateMiddleware.middleware(), 
  SortMiddleware.middleware({ default: "-date" }), 
  blogController.find({
    scopes: ['defaultScope'],
  })
);

routes.get('/posts/:id', isLoggedUser, 
  cacheSuccesses('24 hours'),
  FieldMiddleware.middleware({
    invalidFields: ['updatedAt', 'createdAt']
  }),
  //PaginateMiddleware.middleware(),
  //SortMiddleware.middleware({ default: "date" }), 
  blogController.findOne()
  );

routes.get('/posts/:id/comments', isLoggedUser, 
  PaginateMiddleware.middleware(),
  SortMiddleware.middleware({ default: "-date" }),
  blogController.getPostComments);


/********************************************************************************************************
*  ADMINISTRACIÓN
*********************************************************************************************************
*/
// Todos los posts
routes.get('/admin/posts',
  isAdministratorUser,
  SortMiddleware.middleware({ default: "-date" }),
  blogController.find({
    scopes: ['includeMultimedias', 'includeCategories'],
  })
);

routes.get('/admin/posts/:id', isLoggedUser, 
  isAdministratorUser,
  blogController.findOne({
    scopes: ['includeMultimedias', 'includeCategories'],
  })
);

routes.get('/admin/posts/:id/comments', isLoggedUser,
  isAdministratorUser,
  (req, res, next) => {
    req.params.association = 'comments';
    next();
  },
  blogController.find()
);

routes.post('/admin/posts', isAdministratorUser, blogController.create());
routes.put('/admin/posts/:id', isAdministratorUser, blogController.update());
routes.delete('/admin/posts/:id', isAdministratorUser, blogController.delete());

module.exports = routes;