{"size": 1538, "ext": "js", "max_stars_repo_path": "server/index.js", "max_stars_repo_name": "v-i-n-y-a/ueni", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "server/index.js", "max_issues_repo_name": "v-i-n-y-a/ueni", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/index.js", "max_forks_repo_name": "v-i-n-y-a/ueni", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.4814814815, "max_line_length": 100, "alphanum_fraction": 0.6235370611}
const path = require('path');
const businesses = require('./data/businesses-data.json');
const reviews = require('./data/reviews-data.json');
const isEmpty = require('lodash/isEmpty');
const find = require('lodash/find');
const flatten = require('lodash/flatten');

function getReviews(req, res) {
  if (isEmpty(req.query)) return res.json(reviews);
  const business = Number(req.query.business);
  if (business) {
    const reviewsList = flatten(Object.values(reviews));
    const businessReview = reviewsList.filter( ({ business_id, score }) => business_id === business)
    return res.json(businessReview || {})
  }
  return res.json({})
}

function getBusinesses(req, res) {
  if (isEmpty(req.params)) return res.json(businesses);
  const id = req.params.id;
  if (id) {
    const business = find(businesses, {id: Number(id)}) 
    return res.json(business || {})
  }
  return res.json({})
}

module.exports = function (app) {

    app.get('/', function (req, res) {
        res.sendFile(path.resolve(__dirname, './../index.html'));
    });
    
    app.get('/details/:id', function (req, res) {
        res.sendFile(path.resolve(__dirname, './../index.html'));
    });

    app.get('/api/businesses', getBusinesses);

    app.get('/api/businesses/:id', getBusinesses);

    app.get('/api/reviews', getReviews);

    app.get('/favicon.ico', function (req, res) {
        res.writeHead(204, {
            'Content-Type': 'image/x-icon',
            'Cache-Control': 'public, max-age: 604800'
        });

        res.end();
    });
};
