package handlers_test

import (
	"net/http"
	"testing"

	"otaupdate/handlers"
	"otaupdate/services"

	m "github.com/fiskerinc/cloud-services/pkg/common"
	dbtc "github.com/fiskerinc/cloud-services/pkg/db/queries/mocks"
	htc "github.com/fiskerinc/cloud-services/pkg/httpclient/tester"
	"github.com/fiskerinc/cloud-services/pkg/mongo"
	"github.com/fiskerinc/cloud-services/pkg/redis"
	rtc "github.com/fiskerinc/cloud-services/pkg/redis/tester"
	th "github.com/fiskerinc/cloud-services/pkg/testhelper"
	tr "github.com/fiskerinc/cloud-services/pkg/testrunner"
	"github.com/fiskerinc/cloud-services/pkg/utils/elptr"
)

func TestFleetUpdate(t *testing.T) {
	mockDB := dbtc.MockCars{}
	services.GetDB().SetCars(&mockDB)
	vin := "1G1FP87S3GN100062"
	trexKey := m.TRex.Key(vin)
	cacheKey := redis.CarConfigKey(vin)

	client, err := services.GetMongoClient()
	if err != nil {
		t.Error(err)
		return
	}
	mockMongoFleets := mongo.NewFleetsCollection(&mongo.MockCollection{})
	mockMongoVehicles := mongo.NewVehiclesCollection(&mongo.MockCollection{})
	client.SetFleets(mockMongoFleets)
	client.SetVehicles(mockMongoVehicles)

	mockRedis := rtc.MockRedis{}
	services.SetRedisClientPool(rtc.NewMockClientPool(&mockRedis))

	tests := []tr.TestCase{
		{
			Name: "No data",
			HttpTestCase: &htc.HttpTestCase{
				Request:          th.MakeTestRequest(http.MethodPost, "http://example.com/fleet/TESTFLEET", nil),
				ExpectedStatus:   http.StatusBadRequest,
				ExpectedResponse: `{"message":"primary key required","error":"Bad Request"}`,
			},
		},
		{
			Name: "Invalid data",
			HttpTestCase: &htc.HttpTestCase{
				Request:          th.MakeTestRequest(http.MethodPost, "http://example.com/fleet/TESTFLEET", mongo.Fleet{Name: "TEST_FLEET"}),
				ExpectedStatus:   http.StatusBadRequest,
				ExpectedResponse: `{"message":"primary key required","error":"Bad Request"}`,
			},
		},
		{
			Name: "Valid data 1",
			HttpTestCase: &htc.HttpTestCase{
				Request:          th.MakeTestRequest(http.MethodPut, "http://example.com/fleet/TESTFLEET", mongo.Fleet{Name: "TESTFLEET"}),
				ExpectedStatus:   http.StatusOK,
				ExpectedResponse: `{"name":"TESTFLEET","log_level":"trace","canbus":{"enabled":false,"data_logger_enabled":false,"dtc_enabled":false},"idps_enabled":false,"tags":null,"vehicles":null,"vehicles_count":0}`,
			},
			RedisTestCase: &rtc.RedisTestCase{
				ExpectedMessages: nil,
				ExpectedCaches:   nil,
			},
		},
		{
			Name: "Valid data 2",
			HttpTestCase: &htc.HttpTestCase{
				Request: th.MakeTestRequest(http.MethodPut, "http://example.com/fleet/TESTFLEET",
					mongo.Fleet{
						VehiclesCount: 1,
						Vehicles:      []string{vin},
						Name:          "TESTFLEET",
						LogLevel:      m.Info,
						CANBus: m.CANBus{
							Enabled:    true,
							DTCEnabled: elptr.ElPtr(false),
						},
						DebugMask:   "12",
						IDPSEnabled: true,
					},
				),
				ExpectedStatus:   http.StatusOK,
				ExpectedResponse: `{"name":"TESTFLEET","log_level":"info","canbus":{"enabled":true,"data_logger_enabled":false,"dtc_enabled":false},"idps_enabled":true,"debug_mask":"12","tags":null,"vehicles":["1G1FP87S3GN100062"],"vehicles_count":1}`,
				Setup: func() {
					mockMongoFleets = mongo.NewFleetsCollection(&mongo.MockCollection{
						AggregateObject: []mongo.Fleet{
							{
								Name: "US-TEST",
								Vehicles: []string{
									vin,
								},
							},
						},
					})
					client.SetFleets(mockMongoFleets)
				},
			},
			RedisTestCase: &rtc.RedisTestCase{
				ExpectedMessages: map[string]string{
					trexKey: `{"data":{"canbus":{"data_logger_enabled":false,"dtc_enabled":false,"enabled":true},"idps_enabled":true,"log_level":"info"},"handler":"config"}`,
				},
				ExpectedCaches: map[string]rtc.ExpiringCacheResult{
					cacheKey: {Value: "DELETED"},
				},
			},
		},
	}

	schemaTesterTRex := th.NewSchemaTestHelper(t, schemaToTRex)
	for _, test := range tests {
		mockRedis.Reset()

		if test.DBTestCase != nil {
			test.DBTestCase.SetupDB(&mockDB)
		}
		if test.RedisTestCase != nil {
			test.RedisTestCase.SetupRedis(&mockRedis)
		}

		if test.HttpTestCase != nil {
			if test.HttpTestCase.Setup != nil {
				test.HttpTestCase.Setup()
			}

			w := test.HttpTestCase.TestWithParamPath(handlers.HandleFleetUpdate, "/fleet/:name")
			test.HttpTestCase.ValidateHttp(t, test.Name, w)
		}
		if test.DBTestCase != nil {
			test.DBTestCase.Validate(t, test.Name, &mockDB)
		}
		if test.RedisTestCase != nil {
			test.RedisTestCase.Validate(t, test.Name, &mockRedis)

			for _, mes := range test.RedisTestCase.ExpectedMessages {
				schemaTesterTRex.ValidateSchemaObject(test.Name, []byte(mes))
			}
		}
	}
}
