package handlers

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

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

// GetCarConfiguration godoc
// @Summary Get the vod and cds for car. Does not generate a usable to send to the car
// @Description Get all sap codes for a car, transform them to VOD and CDS, then return it to the user
// @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 to get configuration update"
// @Param forced query bool false "Force configuration update"
// @Success 200 {object} common.UpdateConfigManifest
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /car_config/{vin} [get]
func GetCarConfiguration(w http.ResponseWriter, r *http.Request) {
	params := httprouter.ParamsFromContext(r.Context())
	vin := params.ByName("vin")

	queryParams := r.URL.Query()
	forced, _ := strconv.ParseBool(queryParams.Get("forced"))

	rds := services.RedisClientPool().GetFromPool()
	defer rds.Close()
	cs := services.GetVehicleConfig()
	db := services.GetDB()
	sms := services.GetSMSClient()

	username := httphandlers.GetClientID(r)

	manifestSender := manifestsender.NewTBOXManifestSender(rds, cs, db, sms, nil)
	input := manifestsender.ProcessConfigUpdateStruct{
		VIN:                     vin,
		Username:                username,
		SendToCar:               false,
		DontCreateDatabaseEntry: true,
		Forced:                  forced,
	}
	ucm, err := manifestSender.ProcessConfigUpdate(input, services.GetDB().GetCarConfigData())
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	utils.RespJSON(w, http.StatusOK, ucm)
}
