package handlers_test

import (
	"fmt"
	"net/http"
	"testing"

	"otaupdate/handlers"
	"otaupdate/services"

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

	"github.com/google/uuid"
)

func TestSubscriptionConfigUpdate(t *testing.T) {
	mock := mocks.MockSubscriptionConfigurations{}
	services.GetDB().SetSubConfigurations(&mock)
	testUUID := uuid.MustParse("0557bd1d-76d3-41e5-a44e-13c479e55ab0")
	testConfiguration := common.BinaryHex{0x46, 0x44, 0x73, 0x81}
	testDID := common.BinaryHex{0x32, 0x45}
	testPID := common.BinaryHex{0xAA, 0xAA}
	testMask := common.BinaryHex{0x00, 0x00, 0x00, 0x10}
	validData := common.SubscriptionConfiguration{
		SubscriptionFeatureID: testUUID,
		ECU:                   "TBOX",
		SoftwareVersion:       "SoftwareVersion",
		HardwareVersion:       "HardwareVersion",
		Configuration:         &testConfiguration,
		DID:                   &testDID,
		PID:                   &testPID,
		Mask:                  &testMask,
	}

	tests := []mocks.DBHttpTest{
		{
			Name:             "No data",
			Request:          th.MakeTestRequest(http.MethodPut, "http://example.com/subscriptionconfig", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"SubscriptionFeatureID required. ECU required. SoftwareVersion required. HardwareVersion required. Configuration required. DID required. PID required. Mask required","error":"Bad Request"}`,
		},
		{
			Name: "Missing PK",
			Request: th.MakeTestRequest(http.MethodPut, "http://example.com/subscriptionconfig", common.SubscriptionConfiguration{
				SoftwareVersion: "SoftwareVersion",
				HardwareVersion: "HardwareVersion",
				Configuration:   &testConfiguration,
				DID:             &testDID,
				PID:             &testPID,
				Mask:            &testMask,
			}),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"SubscriptionFeatureID required. ECU required","error":"Bad Request"}`,
		},
		{
			Name:             "Good data",
			Request:          th.MakeTestRequest(http.MethodPut, "http://example.com/subscriptionconfig", validData),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"feature_id":"0557bd1d-76d3-41e5-a44e-13c479e55ab0","ecu":"TBOX","sw_version":"SoftwareVersion","hw_version":"HardwareVersion","configuration":"46447381","did":"3245","pid":"aaaa","mask":"00000010"}`,
		},
		{
			Name:             "Error",
			Request:          th.MakeTestRequest(http.MethodPut, "http://example.com/subscriptionfeature", validData),
			ExpectedStatus:   http.StatusServiceUnavailable,
			ExpectedResponse: `{"message":"something went wrong","error":"Service Unavailable"}`,
			DBTestCase: mocks.DBTestCase{
				MockError: fmt.Errorf("something went wrong"),
			},
		},
	}

	mocks.RunDBTests(t, tests, handlers.HandleSubscriptionConfigUpdate, &mock)
}
