"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _FleetService = _interopRequireDefault(require("../services/FleetService"));

var _AuthService = _interopRequireDefault(require("../services/AuthService"));

var _authMiddleware = _interopRequireDefault(require("../hooks/authMiddleware"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * 
 * @param {import("fastify").FastifyInstance} fastifyInstance 
 * @param {import("fastify").FastifyPluginOptions} options 
 */
const infraRouter = async fastifyInstance => {
  const fleetService = _FleetService.default.getInstance();

  fastifyInstance.get('/', {
    preHandler: (0, _authMiddleware.default)([])
  }, async (request, reply) => {
    reply.status(200).send({
      message: 'OK',
      data: {
        fleets: fleetService.fleets,
        instances: fleetService.instances
      }
    });
  });
  fastifyInstance.post('/fleets', {
    preHandler: (0, _authMiddleware.default)([])
  }, async (request, reply) => {
    const {
      name,
      url,
      token
    } = request.body || {};
    let isValid = await fleetService.validate(url, token);

    if (!isValid) {
      return reply.status(422).send({
        message: 'FAIL',
        cause: 'fleet registry is not available'
      });
    }

    try {
      let fleet = await fleetService.register(name, url, token);
      return reply.status(200).send({
        message: 'OK',
        data: fleet
      });
    } catch (error) {
      return reply.status(500).send({
        message: 'FAIL',
        cause: error.message
      });
    }
  });
  fastifyInstance.delete('/fleets/:fleetId', {
    preHandler: (0, _authMiddleware.default)([])
  }, async (request, reply) => {
    const {
      fleetId
    } = request.params;

    try {
      await fleetService.remove(fleetId);
      return reply.status(200).send({
        message: 'OK'
      });
    } catch (error) {
      return reply.status(422).send({
        message: 'FAIL',
        cause: error.message
      });
    }
  });
  fastifyInstance.get('/fleets', {
    preHandler: (0, _authMiddleware.default)([])
  }, (request, reply) => {
    reply.status(200).send({
      message: 'OK',
      data: fleetService.fleets
    });
  });
  fastifyInstance.get('/instances', {
    preHandler: (0, _authMiddleware.default)([])
  }, (request, reply) => {
    reply.status(200).send({
      message: 'OK',
      data: fleetService.instances
    });
  });
};

var _default = infraRouter;
exports.default = _default;