package cachev2

import (
	"fmt"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db/queries"
	redis "github.com/fiskerinc/cloud-services/pkg/redisv2"

	"github.com/pkg/errors"
)

// VerifyCarToDriver checks cache and DB for car to driver relationship.
// If relationship exists and not in cache, will cache value.
//
//	car:<VIN>:driver:<DRIVER_ID>
func VerifyCarToDriver(clientPool redis.ClientInterface, db queries.CarsInterface, vin string, driverID string) (bool, error) {
	key := redis.CarToDriverKey(vin, driverID)

	ok, err := redisCheckGet(clientPool, key)
	if err != nil {
		return ok, err
	}

	if ok {
		return ok, err
	}

	carToDrivers, err := db.SelectCarToDriver(&common.CarToDriver{VIN: vin, DriverID: driverID})
	if err != nil {
		return false, err
	}
	verified := len(carToDrivers) == 1
	redisPlaceDriverCache(clientPool, key, verified)

	return verified, err
}

func redisCheckGet(redisClient redis.ClientInterface, key string) (bool, error) {
	value, err := redisClient.Get(key)
	if err != nil {
		if errors.Is(err, redis.ErrNil) {
			err = nil
		}
		return false, err
	}
	v, ok := value.(bool)
	if !ok {
		err = fmt.Errorf("failed to convert %v interface to bool", value)
	}
	return v, err
}

func redisPlaceDriverCache(redisClient redis.ClientInterface, key string, verified bool) (err error) {
	batch := redis.NewRedisBatchCommands()
	batch.Add(redis.Command{Command: "SET", Arguments: []interface{}{key, verified}})
	batch.Add(redis.Command{Command: "EXPIRE", Arguments: []interface{}{key, redisObjectExpire.Seconds()}})
	_, err = redisClient.ExecuteBatch(batch)
	return
}
