package handlers

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

	"github.com/fiskerinc/cloud-services/pkg/common"
	orm "github.com/fiskerinc/cloud-services/pkg/db/queries"
	"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"
)

// HandleVersionLogsGet godoc
// @Summary Returns version change logs by VIN.
// @Description Returns version change logs by VIN.
// @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"
// @Success 200 {object} common.CarVersionLogs
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 404 {object} common.JSONError "Not Found"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /vehicle/{vin}/version/logs [get]
func HandleVersionLogsGet(w http.ResponseWriter, r *http.Request) {
	options, err := orm.ParsePageQuery(r)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

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

	_, err = services.GetDB().GetCars().SelectByVIN(vin)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	logs, total, err := services.GetDB().GetCarVersionsLog().SelectByVIN(vin, options)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

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