package server

import (
	"net/http"
	"strconv"

	"github.com/labstack/echo/v4"

	"git.maze.io/ham/hamview/schema"
)

// handleGetAPRSPackets returns APRS packets based on filter criteria.
//
// Endpoint: GET /api/v1/aprs/packets
//
// Query Parameters (evaluated in order):
//   - src: APRS source callsign (case-insensitive)
//   - dst: APRS destination callsign (case-insensitive)
//   - limit: Maximum number of recent packets (default: 100)
//   - (no parameters): Returns the 100 most recent packets
//
// Response: 200 OK
//
//	[]APRSPacket - Array of APRS packet objects
//
// Response: 500 Internal Server Error
//
//	ErrorResponse - Error retrieving packets
//
// Example Requests:
//
//	GET /api/v1/aprs/packets
//	GET /api/v1/aprs/packets?src=OE1ABC
//	GET /api/v1/aprs/packets?dst=APRS
//	GET /api/v1/aprs/packets?limit=200
func (s *Server) handleGetAPRSPackets(c echo.Context) error {
	var (
		ctx     = c.Request().Context()
		packets []*schema.APRSPacket
		err     error
	)

	if source := c.QueryParam("src"); source != "" {
		packets, err = schema.GetAPRSPacketsBySource(ctx, source)
	} else if destination := c.QueryParam("dst"); destination != "" {
		packets, err = schema.GetAPRSPacketsByDestination(ctx, destination)
	} else {
		limit := 100
		if value := c.QueryParam("limit"); value != "" {
			if limit, err = strconv.Atoi(value); err != nil {
				return s.apiError(c, err)
			}
		}
		if limit <= 0 {
			limit = 100
		}
		packets, err = schema.GetAPRSPackets(ctx, limit)
	}

	if err != nil {
		return s.apiError(c, err)
	}

	return c.JSON(http.StatusOK, packets)
}
