package handlers

import (
	"encoding/json"

	"github.com/fiskerinc/cloud-services/services/attendant/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/logger"

	"github.com/pkg/errors"
)

// UpdateData extracts update ID from byte slice
type UpdateData struct {
	ID int `json:"id"`
}

// ApproveUpdate updates DB update field and
//
//	sends redis message to vehicle to initialize download
func ApproveUpdate(db *services.DB, id string, data []byte) error {
	logger.Debug().Msgf("ApproveUpdate %s", id)

	client := services.RedisClientPool().GetFromPool()
	defer client.Close()

	// TODO: NEEDS VALIDATION THAT INCOMING ID CAN APPROVE
	//       CAN COME FROM MOBILE OR HMI - NEEDS TO HANDLE BOTH CASES

	var u UpdateData
	err := json.Unmarshal(data, &u)
	if err != nil {
		return errors.WithStack(err)
	}

	update, err := db.ModifyUpdateStatus(u.ID, "approved")
	if err != nil {
		return err
	}
	logger.Debug().Msgf("Sending redis queue- %s, key- %s, hander- %s, data- %v", "attendant", update.VIN, "update_download", u)

	err = client.SafeQueueMessage(
		common.TRex.Key(update.VIN),
		common.Message{
			Handler: "update_download",
			Data:    u,
		},
	)
	if err != nil {
		return err
	}

	return nil
}
