package locations

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

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

func HandleLocation(w http.ResponseWriter, r *http.Request) {
	var location models.Location
	if err := json.NewDecoder(r.Body).Decode(&location); err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	err := core.DB.
		NewSelect().
		Model(&location).
		Where("street = ? AND city = ? AND postal_code = ?", location.Street, location.City, location.PostalCode).
		Scan(context.Background())
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	var events []models.Event
	err = core.DB.
		NewSelect().
		Model(&events).
		Where("location = ? || ', ' || ? || ', ' || ?", location.Street, location.City, location.PostalCode).
		Scan(context.Background())
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	location.Events = &events

	core.JSONSuccess{
		Status:  core.Success,
		Message: "Location retrieved.",
		Data:    location,
	}.Respond(w, http.StatusOK)
}
