package handlers_test

import (
	"net/http"
	"testing"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db/queries/mocks"
	th "github.com/fiskerinc/cloud-services/pkg/testhelper"

	"otaupdate/handlers"
	"otaupdate/services"
)

func TestHandleVehicleECUsGet(t *testing.T) {
	services.GetDB().SetCars(&mocks.MockCars{
		SelectCarECUs: []common.CarECU{
			{
				ECU:          "ECUA",
				Version:      "1000",
				SerialNumber: "serial",
				HWVersion:    "AAAAA",
			},
			{
				VIN:          "JH4KA3240LC800239",
				ECU:          "ECUB",
				Version:      "1001",
				SerialNumber: "serial",
				HWVersion:    "BBBBB",
				Epoch_usec:   1689352536,
			},
			{
				VIN:          "JH4KA3240LC800239",
				ECU:          "ECUB",
				Version:      "1001",
				SerialNumber: "serial",
				HWVersion:    "BBBBB",
			},
		},
	})

	tests := []th.BasicHttpTest{
		{
			Name:             "No parameters",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/vehicleecus", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"vin '' invalid","error":"Bad Request"}`,
		},
		{
			Name:             "Bad VIN",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/vehicleecus?vin=XXXXXXX", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"vin 'XXXXXXX' invalid","error":"Bad Request"}`,
		},
		{
			Name:             "Good VIN",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/vehicleecus?vin=1G1FP87S3GN100062", nil),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"data":[{"ecu":"ECUA","sw_version":"1000","serial_number":"serial","hw_version":"AAAAA","epoch_usec":0},{"vin":"JH4KA3240LC800239","ecu":"ECUB","sw_version":"1001","serial_number":"serial","hw_version":"BBBBB","epoch_usec":1689352536},{"vin":"JH4KA3240LC800239","ecu":"ECUB","sw_version":"1001","serial_number":"serial","hw_version":"BBBBB","epoch_usec":0}],"total":3}`,
		},
		{
			Name:             "Filter on text search",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/vehicleecus?vin=1G1FP87S3GN100062&search=SOMETEST", nil),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"data":[{"ecu":"ECUA","sw_version":"1000","serial_number":"serial","hw_version":"AAAAA","epoch_usec":0}],"total":1}`,
		},
		{
			Name:             "Filter on most recent VIN/ECU record",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/vehicleecus?vin=1G1FP87S3GN100062&unique=true", nil),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"data":[{"ecu":"ECUA","sw_version":"1000","serial_number":"serial","hw_version":"AAAAA","epoch_usec":0},{"vin":"JH4KA3240LC800239","ecu":"ECUB","sw_version":"1001","serial_number":"serial","hw_version":"BBBBB","epoch_usec":1689352536}],"total":2}`,
		},
	}

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