package events

import (
	"context"
	"encoding/json"
	"net/http"

	core "fr.latosa-escrima/core"
	"fr.latosa-escrima/core/models"
)

func HandleNew(w http.ResponseWriter, r *http.Request) {
	var event models.Event
	err := json.NewDecoder(r.Body).Decode(&event)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusBadRequest)
		return
	}

	_, err = core.DB.NewInsert().Model(&event).Exec(context.Background())
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusNotAcceptable)
		return
	}

	core.JSONSuccess{
		Status:  core.Success,
		Message: "Event created",
		Data:    event,
	}.Respond(w, http.StatusCreated)
}
