package handlers

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

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

var errInvalidVIN = errors.New("invalid VIN entered")

// CarConfigurationUpdate godoc
// @Summary Send VOD and CDS to car
// @Description Get all sap codes for a car, transform them to VOD and CDS, then send it to the car
// @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 send configuration update"
// @Param forced query bool false "Force configuration update"
// @Success 200 {object} common.JSONMessage
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /car_config/{vin} [post]
func CarConfigurationUpdate(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()

	alDB := services.GetDB().GetActionLog()
	actionLog := actionlogger.ActionLog{
		VIN:            vin,
		Action:         actionlogger.CarConfigurationUpdate,
		UserIdentifier: httphandlers.GetClientID(r),
		CallLocation:   "github.com/fiskerinc/cloud-services/services/ota_update_go/handlers/car_configuration_update.go",
	}

	go func() {
		err := alDB.Insert(actionLog)
		if err != nil {
			logger.Err(err).Msg("failed to insert action log inside CarConfigurationUpdate")
		}
	}()

	username := httphandlers.GetClientID(r)

	manifestSender := manifestsender.NewTBOXManifestSender(rds, cs, db, sms, nil)
	input := manifestsender.ProcessConfigUpdateStruct{
		VIN:                     vin,
		Username:                username,
		SendToCar:               true,
		DontCreateDatabaseEntry: false,
		Forced:                  forced,
	}

	// Process and send as this is a new manifest that needs a car update
	_, err := manifestSender.ProcessConfigUpdate(input, services.GetDB().GetCarConfigData())
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	utils.RespJSON(w, http.StatusOK, common.JSONMessage{
		Message: "Sent",
	})
}
