busybar / internal / services / location.service.go
location.service.go
Raw
package services

import (
	"context"

	"github.com/jftuga/geodist"

	"github.com/danielrhuynh/busybar/pkg/database"
)

const (
	ACCEPTABLE_RADIUS_METERS = 100
)

func ValidateUserLocation(barID int, userLat, userLong float64) (bool, error) {
	ctx := context.Background()

	var barLat, barLong float64
	query := `
        SELECT latitude, longitude 
        FROM bars 
        WHERE bar_id = $1
    `

	err := database.DB.QueryRow(ctx, query, barID).Scan(&barLat, &barLong)
	if err != nil {
		return false, err
	}

	userCoord := geodist.Coord{Lat: userLat, Lon: userLong}
	barCoord := geodist.Coord{Lat: barLat, Lon: barLong}
	_, distanceKm, err := geodist.VincentyDistance(userCoord, barCoord)
	if err != nil {
		_, distanceKm = geodist.HaversineDistance(userCoord, barCoord)
	}

	distanceMeters := distanceKm * 1000

	return distanceMeters <= ACCEPTABLE_RADIUS_METERS, nil
}