package handlers

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

	"github.com/fiskerinc/cloud-services/pkg/common"
	orm "github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/julienschmidt/httprouter"
)

// HandleFlashpackVersionECUMappingsGet godoc
// @Summary Get mappings between a flashpack and ecu versions
// @Description Get mappings between a flashpack and ecu versions
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param model path string true "Model"
// @Param trim path string true "Trim"
// @Param year path int true "Year"
// @Param flashpack path string true "Flashpack"
// @Param limit query int false "Max number of records"
// @Param offset query int false "Records offset"
// @Success 200 {object} common.JSONDBQueryResult "Get flashpack ecu mappings result"
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /flashpack_version_ecu_mappings/{model}/{trim}/{year}/{flashpack} [get]
func HandleFlashpackVersionECUMappingsGet(w http.ResponseWriter, r *http.Request) {
	var req common.CarFlashpackVersionRequest
	var err error

	params := httprouter.ParamsFromContext(r.Context())
	req.Flashpack = params.ByName("flashpack")
	req.CarModel = params.ByName("model")
	req.CarTrim = params.ByName("trim")
	req.CarYear, err = strconv.Atoi(params.ByName("year"))
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	options, err := orm.ParsePageQuery(r)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}
	if options.Order == "" {
		options.Order = "created_at DESC"
	}

	cars := services.GetDB().GetCars()

	flashpackMappings, err := cars.GetCarFlashpackVersionMappingsByModelTrimYearFlashpack(req.CarModel, req.CarTrim, req.CarYear, req.Flashpack, options)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	total, err := cars.GetCarFlashpackVersionMappingsByModelTrimYearFlashpackCount(req.CarModel, req.CarTrim, req.CarYear, req.Flashpack)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

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