const express = require("express");
const ClientsService = require("../domain/clients");
const FiltersService = require("../domain/filters");

const { sequelize } = require("../models");

const filteringService = new FiltersService(null, sequelize);
filteringService.addFilter(
  FiltersService.match,
  FiltersService.bestKnowledge,
  FiltersService.bestAvgFeatures,
  FiltersService.bestAvgPrice,
  FiltersService.random
);

const router = express.Router();

router.post("/", async (request, response, next) => {
  try {
    const clientsService = new ClientsService(request.log, sequelize);

    const clients = await clientsService.save(request.body);

    response.status(200).json(clients);
  } catch (error) {
    next(error);
  }
});

router.put("/:id", async (request, response, next) => {
  try {
    const clientsService = new ClientsService(request.log, sequelize);

    const clients = await clientsService.update(request.params.id, request.body);

    response.status(200).json(clients);
  } catch (error) {
    next(error);
  }
});

router.post("/:id/interests", async (request, response, next) => {
  try {
    const clientsService = new ClientsService(request.log, sequelize);

    const interest = request.body;
    const interestObj = await clientsService.saveInterest(request.params.id, interest);

    const staffMember = await filteringService.filter(interest);

    const client = await clientsService.update(request.params.id, { expertId: staffMember.id });

    client.dataValues.interests = interestObj;
    // give back correct data for both client and interests
    response.status(200).json(client);
  } catch (error) {
    if(error.message == "Not found") {
      response.status(404).json({ error: true, message: "No robot matching the criteria!"})
    } else {
      next(error);
    }
  }
});

router.get("/", async (request, response, next) => {
  try {
    const clientsService = new ClientsService(request.log, sequelize);

    const clients = await clientsService.getList(request.query);

    response.status(200).json(clients);
  } catch (error) {
    next(error);
  }
});

router.get("/:id", async (request, response, next) => {
  try {
    const clientsService = new ClientsService(request.log, sequelize);

    const client = await clientsService.getById(request.params.id);
    if (!client) throw new Error("Client not found");
    const interests = await client.getInterests();
    client.dataValues.interests = interests.slice(-1)[0];

    response.status(200).json(client);
  } catch (error) {
    next(error);
  }
});

module.exports = router;
