package v1

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

// AuthorDelete is the handler for deleting an author
func AuthorDelete(c echo.Context) error {

	id := c.Param("id")

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

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

	// Check if the author exists
	_, exists, err := models.GetAuthorByID(authorID)

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

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

	// Delete it
	err = models.DeleteAuthorByID(authorID)

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

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

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