package handlers

import (
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/mongo"
	"github.com/fiskerinc/cloud-services/pkg/utils/envtool"
	"github.com/fiskerinc/cloud-services/pkg/validator"

	"github.com/julienschmidt/httprouter"
	"github.com/pkg/errors"
	mo "go.mongodb.org/mongo-driver/mongo"
)

var logLevel = envtool.GetEnv("TREX_LOG_LEVEL", common.CriticalLabel)

// HandlevehicleGet godoc
// @Summary Get vehicle
// @Description Get vehicle
// @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} mongo.Vehicle
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /vehicle/{vin} [get]
func HandleVehicleGet(w http.ResponseWriter, r *http.Request) {
	vehicleGet.Handle(w, r)
}

var vehicleGet = controllers.NewMongoGetModel(&vehicleGetModelHelper{})

type vehicleGetModelHelper struct{}

func (h *vehicleGetModelHelper) ValidatePK(model interface{}) error {
	result := model.(*mongo.Vehicle)

	err := validator.ValidateField(result.VIN, "required,vin")
	if err != nil {
		return err
	}

	return nil
}

func (h *vehicleGetModelHelper) ParseGetURLParams(r *http.Request) interface{} {
	req := &mongo.Vehicle{}

	params := httprouter.ParamsFromContext(r.Context())
	req.VIN = params.ByName("vin")

	return req
}

func (h *vehicleGetModelHelper) ValidateFields(model interface{}) error {
	result := model.(*mongo.Fleet)

	err := validator.ValidateField(result.Name, "required,fleet")
	if err != nil {
		return controllers.ErrorPKRequired
	}

	return nil
}

func (h *vehicleGetModelHelper) Query(filter interface{}) (interface{}, error) {
	client, err := services.GetMongoClient()
	if err != nil {
		return nil, err
	}

	v := filter.(*mongo.Vehicle)

	c, err := services.GetDB().GetCars().SelectByVIN(v.VIN)
	if err != nil {
		return nil, err
	}

	data, err := client.GetVehicles().FindVehicle(v)

	if err != nil && errors.Cause(err) == mo.ErrNoDocuments {
		data, err = h.createDefault(v, err)
		if err != nil {
			return nil, err
		}
	}

	return &VehicleCar{
		VIN:     v.VIN,
		Car:     c,
		Vehicle: data,
	}, nil
}

func (h *vehicleGetModelHelper) createDefault(vehicle *mongo.Vehicle, err error) (*mongo.Vehicle, error) {
	client, err := services.GetMongoClient()
	if err != nil {
		return nil, err
	}

	vehicle.CANBus = common.CANBus{Enabled: true}
	vehicle.LogLevel = common.UnmarshalLogLevelString(logLevel)
	err = client.GetVehicles().AddVehicle(vehicle)

	return vehicle, err
}

type VehicleCar struct {
	VIN string `json:"vin"`
	*common.Car
	*mongo.Vehicle
}
