package handlers

import (
	"encoding/json"

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

	"github.com/fiskerinc/cloud-services/pkg/cache"
	"github.com/fiskerinc/cloud-services/pkg/common"
	s "github.com/fiskerinc/cloud-services/pkg/common/carupdatestatus"
	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/validator"

	"github.com/pkg/errors"
)

// VehicleData extracts VIN from byte slice
type VehicleData struct {
	VIN string `json:"vin" validate:"required,vin"`
}

// GetUpdates queries DB for updates based off VIN and
//
//	sends redis message back to requester
func GetUpdates(db *services.DB, id string, data []byte) error {
	clientPool := services.RedisClientPool()

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

	err = validator.ValidateStruct(&v)
	if err != nil {
		return errors.WithStack(err)
	}

	ok, err := cache.VerifyCarToDriver(clientPool, db.GetCars(), v.VIN, id)
	if err != nil {
		return err
	} else if !ok {
		return cache.ErrInvalidCarToDriverAssociation(v.VIN, id)
	}

	cu := common.CarUpdate{
		VIN:    v.VIN,
		Status: s.InstallApprovalAwait,
	}
	updates, err := db.GetCarUpdates().Select(&cu, nil)
	if err != nil {
		return err
	}

	result := make([]common.ApprovalUpdate, len(updates))
	for i := range updates {
		result[i] = common.NewApprovalUpdates(&updates[i])
	}

	client := clientPool.GetFromPool()
	defer client.Close()
	logger.Debug().Msgf("Sending redis queue- %s, key- %s, hander- %s, data- %v", "attendant", id, "updates", result)
	return client.SafeQueueMessage(
		common.Mobile.Key(id),
		common.Message{
			Handler: "updates",
			Data:    result,
		},
	)
}
