package handlers_test

import (
	"encoding/json"
	"net/http"
	"otaupdate/handlers"
	"otaupdate/services"
	"testing"
	"time"

	"github.com/fiskerinc/cloud-services/pkg/redis"
	"github.com/fiskerinc/cloud-services/pkg/redis/tester"
	th "github.com/fiskerinc/cloud-services/pkg/testhelper"
)

func TestHandleVehicleState(t *testing.T) {
	timeSerialized, _ := json.Marshal(time.Time{})
	client := tester.NewRedisMock()
	client.SISMEMBEResults = map[string]map[string]interface{}{
		redis.CarSessionsKey(): {"1F15K3R45N1234567": int64(0)},
		redis.HMISessionsKey(): {"1F15K3R45N1234567": int64(0)},
	}
	client.HGETALLResults = map[string][]interface{}{
		redis.CarStateHashKey("1F15K3R45N1234567"): {
			[]byte("location"), []byte(`{}`),
			[]byte("battery"), []byte(`{}`),
			[]byte("doors"), []byte(`{}`),
			[]byte("windows"), []byte(`{}`),
			[]byte("updated"), timeSerialized,
		},
	}
	services.SetRedisClientPool(tester.NewMockClientPool(client))

	tests := []th.BasicHttpTest{
		{
			Name:             "Good request",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/carstate?vin=1F15K3R45N1234567", nil),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"data":{"online":false,"online_hmi":false}}`,
		},
		{
			Name:             "No VIN",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/carstate", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"missing VIN","error":"Bad Request"}`,
		},
		{
			Name:             "Invalid VIN",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/carstate?vin=TESTVIN123", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"invalid VIN","error":"Bad Request"}`,
		},
	}

	th.RunBasicHttpTests(t, tests, handlers.HandleVehicleState)
}

func TestHandleVehicleStateEmpty(t *testing.T) {
	vin := "1F15K3R45N1234567"
	client := tester.NewRedisMock()
	client.SISMEMBEResults = map[string]map[string]interface{}{
		redis.CarSessionsKey(): {vin: int64(0)},
		redis.HMISessionsKey(): {vin: int64(0)},
	}
	client.HGETALLResults = map[string][]interface{}{
		redis.CarStateHashKey(vin): {},
	}
	services.SetRedisClientPool(tester.NewMockClientPool(client))

	tests := []th.BasicHttpTest{
		{
			Name:             "Good request",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/carstate?vin=1F15K3R45N1234567", nil),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"data":{"online":false,"online_hmi":false}}`,
		},
	}

	th.RunBasicHttpTests(t, tests, handlers.HandleVehicleState)
}
