package handlers

import (
	"context"
	"net/http"
	"otaupdate/services"

	"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/utils/urlhelper"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/julienschmidt/httprouter"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

const SqlCHSelectSignals = `SELECT Timestamp, Name, Value
    FROM vehicle_signal_lv
    WHERE
    VIN=$1 and
    Timestamp > $2
	ORDER BY Timestamp DESC LIMIT $3`

// HandleVehiclesSignals godoc
// @Summary Get locations of cars
// @Description Returns car locations
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param vin path string true "VIN"
// @Param limit query int false "Max number of records. Default is 20 if not set"
// @Param after_utc query int false "Time from which we want to see the can signals from"
// @Param after_timestamp query string false "Time from which we want to see the can signals from"
// @Success 200 {object} common.JSONDBQueryResult{data=[]common.ClickHouseSignal}
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /cansignals/{vin} [get]
func HandleVehiclesSignals(w http.ResponseWriter, r *http.Request) {
	params := httprouter.ParamsFromContext(r.Context())
	vin := params.ByName("vin")

	err := validator.ValidateField(vin, "required,vin")
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	qs := r.URL.Query()
	limit := urlhelper.GetQueryInt(qs, "limit")
	if limit == 0 {
		limit = 20
	}

	after := urlhelper.GetQueryUnix(qs, "after_utc")
	a := urlhelper.GetQueryTimeStamp(qs, "after_timestamp")
	if !a.IsZero() {
		after = a
	}

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

		return
	}

	var results []common.ClickHouseSignal

	err = conn.Select(context.Background(), &results, SqlCHSelectSignals, vin, after, limit)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	// If there are no results, Clickhouse returns nil slice
	if len(results) == 0 {
		results = []common.ClickHouseSignal{}
	}

	utils.RespJSON(w, http.StatusOK, common.JSONDBQueryResult{
		Data: results,
	})
}
