package handlers_test

import (
	"fmt"
	"net/http"
	"otaupdate/handlers"
	"otaupdate/services"
	"testing"

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

func TestSubscriptionConfigAdd(t *testing.T) {
	mock := mo.MockSubscriptionConfigurations{}
	services.GetDB().SetSubConfigurations(&mock)
	testFeatureID := 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: testFeatureID,
		ECU:                   "TBOX",
		SoftwareVersion:       "SoftwareVersion",
		HardwareVersion:       "HardwareVersion",
		Configuration:         &testConfiguration,
		DID:                   &testDID,
		PID:                   &testPID,
		Mask:                  &testMask,
	}
	tests := []mo.DBHttpTest{
		{
			Name:             "No data",
			Request:          th.MakeTestRequest(http.MethodPost, "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: "Invalid data",
			Request: th.MakeTestRequest(http.MethodPost, "http://example.com/subscriptionconfig", common.SubscriptionFeature{
				Name: "feature_name",
			}),
			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:             "Valid data",
			Request:          th.MakeTestRequest(http.MethodPost, "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:             "DB error",
			Request:          th.MakeTestRequest(http.MethodPost, "http://example.com/subscriptionconfig", validData),
			ExpectedStatus:   http.StatusServiceUnavailable,
			ExpectedResponse: `{"message":"something went wrong","error":"Service Unavailable"}`,
			DBTestCase: mo.DBTestCase{
				MockError: fmt.Errorf("something went wrong"),
			},
		},
	}

	mo.RunDBTests(t, tests, handlers.HandleSubscriptionConfigAdd, &mock)
}
