package handlers

import (
	"net/http"

	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"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/mongo"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/fiskerinc/cloud-services/pkg/utils/elptr"
	"github.com/fiskerinc/cloud-services/pkg/utils/envtool"
	mon "go.mongodb.org/mongo-driver/mongo"
)

var defaultFleet = envtool.GetEnv("DEFAULT_FLEET", "Default-Ocean")

// HandleVehicleAdd godoc
// @Summary Adds vehicle
// @Description Creates vehicle data
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param car body common.AddCarRequest true "Car data"
// @Success 200 {object} common.AddCarRequest
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /vehicle [post]
func HandleVehicleAdd(w http.ResponseWriter, r *http.Request) {
	var acr common.AddCarRequest
	err := httphandlers.ParseRequest(r, &acr)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	if acr.CANBus == nil {
		acr.CANBus = &common.CANBus{Enabled: true, DTCEnabled: elptr.ElPtr(true)}
	}

	c, err := utils.ParseVIN(acr.VIN)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	_, err = services.GetDB().GetCars().Insert(c)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	client, err := services.GetMongoClient()
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	v := &mongo.Vehicle{VIN: acr.VIN, CANBus: *acr.CANBus, LogLevel: common.UnmarshalLogLevelString(logLevel), IDPSEnabled: acr.IDPSEnabled}
	err = client.GetVehicles().AddVehicle(v)
	if mon.IsDuplicateKeyError(err) {
		logger.Err(err).Msgf("when adding vehicle %s to mongo, received duplicate error from mongodb. car added to postgres but no fleet", acr.VIN)
		return
	}
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		logger.Err(err).Msgf("when adding vehicle %s to mongo, received error, car added to postgres but no fleet", acr.VIN)
		return
	}

	err = client.GetFleets().AddVehiclesToFleet(defaultFleet, []string{acr.VIN})
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	utils.RespJSON(w, http.StatusOK, &acr)
}
