package handlers_test

import (
	"net/http"
	"testing"

	"otaupdate/handlers"
	"otaupdate/services"

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

func TestFleetVehicleGetList(t *testing.T) {
	client, err := services.GetMongoClient()
	if err != nil {
		t.Error(err)
		return
	}
	client.SetFleets(mongo.NewFleetsCollection(
		&mongo.MockCollection{
			AggregateObject: []mongo.Fleet{
				{
					Name: "US-TEST",
					Vehicles: []string{
						"TESTVIN1234567890",
						"TESTVIN1234567891",
					},
				},
			},
		},
	))

	redisClient := tester.NewRedisMock()
	redisClient.SISMEMBEResults = map[string]map[string]interface{}{
		redis.CarSessionsKey(): {
			"TESTVIN1234567890": int64(0),
			"TESTVIN1234567891": int64(1),
		},
		redis.HMISessionsKey(): {
			"TESTVIN1234567890": int64(0),
			"TESTVIN1234567891": int64(1),
		},
	}
	redisClient.HGETALLResults = map[string][]interface{}{
		redis.CarStateHashKey("TESTVIN1234567890"): {
			[]byte("trex_version"), []byte(`1.2.4`),
		},
	}

	services.SetRedisClientPool(tester.NewMockClientPool(redisClient))

	tests := []th.BasicHttpTest{
		{
			Name:             "Invalid vin parameter",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/fleet/$INVALIDTEST/vehicles", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"primary key required","error":"Bad Request"}`,
		},
		{
			Name:             "Valid data",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/fleet/US-TEST/vehicles", nil),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"data":[{"vin":"TESTVIN1234567890","carstate":{"online":false,"online_hmi":false,"trex_version":"1.2.4"},"carupdate":{"vin":"","UpdateSource":""}},{"vin":"TESTVIN1234567891","carstate":{"online":true,"online_hmi":true},"carupdate":{"vin":"","UpdateSource":""}}]}`,
		},
	}

	th.RunParamHttpTests(t, tests, handlers.HandleFleetVehicleGetList, "/fleet/:name/vehicles")
}
