const Benchmark = require('../models').models.Benchmark;
const Result = require('../models').models.Result;
const Test = require('../models').models.Test;

// GET /api/v1/benchmark/details
exports.getBenchmarkDetails = async function(req, res) {
  try {
    const benchmark = await Benchmark.findByPk(req.query.benchmark_id);

    if (!benchmark) {
      return res.status(404).json({
        error: 'Benchmark not found.'
      })
    }

    res.json(benchmark);
  } catch (err) {
    res.status(500).json({
      error: 'Internal server error occurred while fetching benchmark details.'
    });
  }
};

// GET /api/v1/result/list - list of results for a test
exports.getResultList = async function(req, res) {
  try {
    var results = await Result.findAll({
      where: {
        TestId: req.query.test_id,
        BenchmarkId: req.query.benchmark_id
      }
    });

    res.json(results);
  } catch (err) {
    res.status(500).json({
      error: 'Internal server error occurred while fetching benchmark results.'
    });
  }
};

// POST /api/v1/result/add - add a benchmark result to the database
exports.postResultAdd = async function(req, res) {
  try {
    const result = await Result.create({
      avgScore: req.body.result_avg,
      minScore: req.body.result_min,
      maxScore: req.body.result_max
    });

    let benchmark = await Benchmark.findByPk(req.body.result_benchmark);
    result.setBenchmark(benchmark);

    let test = await Test.findByPk(req.body.result_test);
    result.setTest(test);

    res.json('success');
  } catch (err) {
    res.status(500).json({
      error: 'Internal server error occurred while adding result.'
    });
  }
};
