busybar / internal / controllers / reports.controller.go
reports.controller.go
Raw
package controllers

import (
	"net/http"

	"github.com/danielrhuynh/busybar/internal/auth"
	"github.com/danielrhuynh/busybar/internal/models"
	"github.com/danielrhuynh/busybar/internal/services"

	"github.com/go-playground/validator/v10"
	"github.com/labstack/echo/v4"
)

var validate = validator.New()

func CreateReport(c echo.Context) error {
	var req models.Report
	if err := c.Bind(&req); err != nil {
		return c.JSON(http.StatusBadRequest, envelope{
			"error": "Invalid request payload",
		})
	}

	isInGeofence, err := services.ValidateUserLocation(req.BarID, req.Latitude, req.Longitude)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, envelope{
			"error": "Failed to validate location",
		})
	}

	if !isInGeofence {
		return c.JSON(http.StatusForbidden, envelope{
			"error": "You must be at the bar to report wait times",
		})
	}

	userSession, err := auth.GetUser(c)
	if err != nil {
		return c.JSON(http.StatusUnauthorized, envelope{
			"error": "Unauthorized",
		})
	}

	if err := validate.Struct(req); err != nil {
		return c.JSON(http.StatusBadRequest, envelope{
			"error": err.Error(),
		})
	}

	err = services.CreateReport(userSession.ID, &req)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, envelope{
			"error":   "Failed to create report",
			"details": err.Error(),
		})
	}

	return c.JSON(http.StatusCreated, envelope{
		"report": req,
	})
}

func GetUserWaitTimes(c echo.Context) error {
	userSession, err := auth.GetUser(c)
	if err != nil {
		return c.JSON(http.StatusUnauthorized, envelope{
			"error": "Unauthorized",
		})
	}

	reports, err := services.GetWaitTimesByUserID(userSession.ID)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, envelope{
			"error": "Failed to retrieve reports",
		})
	}
	return c.JSON(http.StatusOK, envelope{
		"reports": reports,
	})
}

func GetAverageWaitTimes(c echo.Context) error {
	averages, err := services.GetAverageWaitTimes()
	if err != nil {
		return c.JSON(http.StatusInternalServerError, envelope{
			"error": "Failed to retrieve average wait times",
		})
	}

	return c.JSON(http.StatusOK, envelope{
		"average_wait_times": averages,
	})
}