package controllers

import (
	"api/database"
	"api/models"
	"api/utils"

	"github.com/gofiber/fiber/v2"
)

// AddServer - Adds a server to the database
func AddServer(c *fiber.Ctx) error {

	var data map[string]string

	if err := c.BodyParser(&data); err != nil {
		return fiber.ErrBadRequest
	}

	if data["name"] == "" || data["ip"] == "" {
		return fiber.ErrBadRequest
	}

	server := models.Server{
		Name: data["name"],
		IP:   data["ip"],
	}

	database.DB.Create(&server)

	if server.Id == 0 {
		return fiber.ErrNotAcceptable
	}

	return c.JSON(server)
}

// GetAllServers - Returns all servers
func GetAllServers(c *fiber.Ctx) error {

	var servers []models.Server

	_, err := utils.ProcessToken(c)
	if err != nil {
		return fiber.ErrUnauthorized
	}

	database.DB.Find(&servers)

	if len(servers) == 0 {
		return fiber.ErrNotFound
	}

	return c.JSON(servers)
}
