package v1

import (
	"git.mowie.cc/konrad/Library/models"
	"github.com/labstack/echo"
	"net/http"
	"strconv"
)

// PublisherDelete is the handler to delete a publisher
func PublisherDelete(c echo.Context) error {

	id := c.Param("id")

	// Make int
	publisherID, err := strconv.ParseInt(id, 10, 64)

	if err != nil {
		return c.JSON(http.StatusBadRequest, models.Message{"Publisher ID is invalid."})
	}

	// Check if the publisher exists
	_, exists, err := models.GetPublisherByID(publisherID)

	if err != nil {
		return c.JSON(http.StatusInternalServerError, models.Message{"Could not get publisher."})
	}

	if !exists {
		return c.JSON(http.StatusNotFound, models.Message{"The publisher does not exist."})
	}

	// Delete it
	err = models.DeletePublisherByID(publisherID)

	if err != nil {
		return c.JSON(http.StatusInternalServerError, models.Message{"Could not delete publisher."})
	}

	// Log the action
	err = models.LogAction("Deleted a publisher", publisherID, c)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, models.Message{"Could not log."})
	}

	return c.JSON(http.StatusOK, models.Message{"success"})
}
