package handlers_test

import (
	"net/http"
	"testing"

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

	"otaupdate/handlers"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/mongo"
	th "github.com/fiskerinc/cloud-services/pkg/testhelper"
	"github.com/fiskerinc/cloud-services/pkg/utils/elptr"
)

func TestVehicleFilterAdd(t *testing.T) {
	client, err := services.GetMongoClient()
	if err != nil {
		t.Error(err)
		return
	}
	mockMongo := mongo.NewVehiclesCollection(&mongo.MockCollection{})
	client.SetVehicles(mockMongo)

	conn := tester.NewRedisMock()
	conn.SetValues = map[string]tester.ExpiringCache{
		redis.CarConfigKey("2D4FV48T95H646760"): {
			Value: nil,
		},
	}
	services.SetRedisClientPool(tester.NewMockClientPool(conn))

	tests := []th.BasicHttpTest{
		{
			Name:             "Invalid vin parameter",
			Request:          th.MakeTestRequest(http.MethodPost, "http://example.com/vehicle/TESTVIN123/filter", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"CANID required","error":"Bad Request"}`,
		},
		{
			Name:             "Invalid data",
			Request:          th.MakeTestRequest(http.MethodPost, "http://example.com/vehicle/2D4FV48T95H646760/filter", common.CANFilter{}),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"CANID required","error":"Bad Request"}`,
		},
		{
			Name:             "Invalid data with can id",
			Request:          th.MakeTestRequest(http.MethodPost, "http://example.com/vehicle/2D4FV48T95H646760/filter", common.CANFilter{CANID: "123"}),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"At least one of edge_mask or interval is required","error":"Bad Request"}`,
		},
		{
			Name: "Invalid data with all fields",
			Request: th.MakeTestRequest(http.MethodPost, "http://example.com/vehicle/2D4FV48T95H646760/filter",
				common.CANFilter{CANID: "123", EdgeMask: elptr.ElPtr(common.BinaryHex("123")), Interval: elptr.ElPtr(1)}),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"Only one of edge_mask or interval can be specified","error":"Bad Request"}`,
		},
		{
			Name: "Valid data",
			Request: th.MakeTestRequest(http.MethodPost, "http://example.com/vehicle/2D4FV48T95H646760/filter",
				common.CANFilter{CANID: "123", Interval: elptr.ElPtr(100)}),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"can_id":"123","interval":100}`,
		},
	}

	th.RunParamHttpTests(t, tests, handlers.HandleVehicleFilterAdd, "/vehicle/:vin/filter")
}
