package handlers_test

import (
	"net/http"
	"testing"

	"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 TestFleetFilterUpdate(t *testing.T) {
	client, err := services.GetMongoClient()
	if err != nil {
		t.Error(err)
		return
	}
	mockMongo := mongo.NewFleetsCollection(&mongo.MockCollection{})
	client.SetFleets(mockMongo)

	tests := []th.BasicHttpTest{
		{
			Name: "Invalid data",
			Request: th.MakeTestRequest(http.MethodPut, "http://example.com/fleet/US-TEST/filter/123",
				common.CANFilter{Interval: elptr.ElPtr(0)}),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"CANID required","error":"Bad Request"}`,
		},
		{
			Name: "Valid data",
			Request: th.MakeTestRequest(http.MethodPut, "http://example.com/fleet/US-TEST/filter/123",
				common.CANFilter{CANID: "123", Interval: elptr.ElPtr(100)}),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"can_id":"123","interval":100}`,
		},
		{
			Name:             "Invalid data with can id",
			Request:          th.MakeTestRequest(http.MethodPost, "http://example.com/fleet/US-TEST/filter/123", 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/fleet/US-TEST/filter/123",
				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"}`,
		},
	}

	th.RunParamHttpTests(t, tests, handlers.HandleFleetFilterUpdate, "/fleet/:name/filter/:id")
}
