package api

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"

	"github.com/tidbcloud/alertstore/pkg/event"
)

// @Summary	List the monitor events alerts were raised from
// @Id			listEvents
// @Tags		Events
// @Produce	json
// @Param		alertname			query		string	false	"Alert name"
// @Param		classification		query		string	false	"page or ticket; comma-separate to match any of several"
// @Param		cluster_id			query		string	false	"Cluster id"
// @Param		tenant_id			query		string	false	"Tenant id"
// @Param		region				query		string	false	"Cloud region"
// @Param		biz_region			query		string	false	"Business region"
// @Param		tenant_kind			query		string	false	"Tenant kind"
// @Param		customer_type		query		string	false	"Customer type"
// @Param		status				query		string	false	"firing or resolved; comma-separate to match any of several"
// @Param		observation_type	query		string	false	"first_firing, repeat_firing, or resolved; comma-separate to match any of several"
// @Param		limit				query		int		false	"Page size"		default(50)
// @Param		offset				query		int		false	"Page offset"	default(0)
// @Success	200					{array}		event.Event
// @Failure	500					{object}	ErrorResponse
// @Router		/events [get]
func (s *Server) listEvents(c *gin.Context) {
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "50"))
	offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))

	events, err := s.eventStore.List(c.Request.Context(), event.ListFilter{
		Alertname:        c.Query("alertname"),
		Classifications:  splitCSV(c.Query("classification")),
		ClusterID:        c.Query("cluster_id"),
		TenantID:         c.Query("tenant_id"),
		Region:           c.Query("region"),
		BizRegion:        c.Query("biz_region"),
		TenantKind:       c.Query("tenant_kind"),
		CustomerType:     c.Query("customer_type"),
		Statuses:         splitCSV(c.Query("status")),
		ObservationTypes: splitCSV(c.Query("observation_type")),
		Limit:            limit,
		Offset:           offset,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, errorBody(err))
		return
	}
	c.JSON(http.StatusOK, events)
}

// @Summary	Get one monitor event
// @Id			getEvent
// @Tags		Events
// @Produce	json
// @Param		id	path		int	true	"Event id"
// @Success	200	{object}	event.Event
// @Failure	400	{object}	ErrorResponse
// @Failure	404	{object}	ErrorResponse
// @Router		/events/{id} [get]
func (s *Server) getEvent(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, errorMessage("invalid event id"))
		return
	}

	e, err := s.eventStore.GetByID(c.Request.Context(), id)
	if err != nil {
		c.JSON(http.StatusNotFound, errorMessage("event not found"))
		return
	}
	c.JSON(http.StatusOK, e)
}
