package handlers

import (
	"context"
	"errors"
	"net/http"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/grpc/sms"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

// HandleSendWakeSMSToVIN godoc
// @Summary Get overall software version from a car and its ecu version information
// @Description Get overall software version from a car and its ecu version information
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param vin query string true "VIN"
// @Success 200 {object} string "Message Status String"
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /car/wake [post]
func HandleSendWakeSMSToVIN(w http.ResponseWriter, r *http.Request) {
	qs := r.URL.Query()
	vin := qs.Get("vin")
	if vin == "" {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("missing vin"))
		return
	}

	status, err := sendWakeSMSToVIN(vin)
	if loggerdataresp.BadDataError(err) {
		return
	}
	w.Write([]byte(status))
}

// Sends wak up SMS along with CAN Status wak
func sendWakeSMSToVIN(vin string) (status string, err error) {
	car, err := services.GetDB().GetCars().SelectByVIN(vin)
	if err != nil {
		return "failed", err
	}
	if car == nil {
		return "failed", errors.New("vehicle not found")
	}

	iccid := car.ICCID

	k := sms.SendSMSRequest{
		ICCID:       iccid,
		MessageText: "wake",
		Await:       true,
	}
	res, err := services.GetSMSClient().HandleSMSSend(context.Background(), &k)
	if err != nil {
		return "failed", err
	}
	// Send the can bus wake up command
	err = sendCANAwakeToVIN(vin)
	if err != nil {
		return "failed can awake", err
	}
	return res.Status.String(), nil
}

func sendCANAwakeToVIN(vin string) (err error) {
	err = services.GetRedisV2Client().SafeQueueMessage(common.TRex.Key(vin), common.Message{
		Handler: "can_network",
		Data:    common.RemoteCANNetworkCommandArgs{Action: "on", Timeout: 180},
	})
	return err
}
