package handlers

import (
	"net/http"

	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/clickhouse"
	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/fiskerinc/cloud-services/pkg/validator"

	"github.com/julienschmidt/httprouter"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

// HandleDBCSignalsGetList godoc
// @Summary List API tokens
// @Description List API tokens. Requires API token permission
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param limit query int false "Max number of records"
// @Param offset query int false "Records offset"
// @Param dbc path string true "DBC hash"
// @Success 200 {object} common.JSONDBQueryResult{data=[]common.SignalDescWithECU}
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /can_signals/{dbc} [get]
func HandleDBCSignalsGetList(w http.ResponseWriter, r *http.Request) {
	options, err := clickhouse.ParsePageQuery(r)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	params := httprouter.ParamsFromContext(r.Context())
	dbc := params.ByName("dbc")
	err = validator.GetValidator().Var(dbc, "required")
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	cl, err := services.GetClickhouseClient()
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		logger.Error().Err(err).Msg("cannot get clickhouse client")

		return
	}

	signals, count, err := cl.SelectDBCSignals(dbc, options)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	utils.RespJSON(w, http.StatusOK, common.JSONDBQueryResult{Data: signals, Total: count})
}
