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 TestSubscriptionPackageUpdate(t *testing.T) {
	mock := mocks.MockSubscriptionPackages{}
	services.GetDB().SetSubPackages(&mock)
	testUUID := uuid.MustParse("0557bd1d-76d3-41e5-a44e-13c479e55ab0")
	reqGoodData := common.SubscriptionPackage{
		ID:   testUUID,
		Name: "Test",
	}

	tests := []mocks.DBHttpTest{
		{
			Name:             "No data",
			Request:          th.MakeTestRequest(http.MethodPut, "http://example.com/subscriptionpackage", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"Name required","error":"Bad Request"}`,
		},
		{
			Name: "Missing PK",
			Request: th.MakeTestRequest(http.MethodPut, "http://example.com/subscriptionpackage", common.SubscriptionPackage{
				Name: "Test",
			}),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"primary key required","error":"Bad Request"}`,
		},
		{
			Name: "Bad Data",
			Request: th.MakeTestRequest(http.MethodPut, "http://example.com/subscriptionpackage", common.SubscriptionPackage{
				ID:   testUUID,
				Name: "",
			}),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"Name required","error":"Bad Request"}`,
		},
		{
			Name:             "Good data",
			Request:          th.MakeTestRequest(http.MethodPut, "http://example.com/subscriptionpackage", reqGoodData),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"id":"0557bd1d-76d3-41e5-a44e-13c479e55ab0","name":"Test"}`,
		},
		{
			Name:             "Error",
			Request:          th.MakeTestRequest(http.MethodPut, "http://example.com/subscriptionpackage", reqGoodData),
			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.HandleSubscriptionPackageUpdate, &mock)
}
