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"
)

func TestAPITokenUpdate(t *testing.T) {
	mock := mocks.MockAPITokens{}
	services.GetDB().SetAPITokens(&mock)
	validData := common.APIToken{
		Token:       "TESTTOKEN",
		Roles:       "TESTROLES1,TESTROLES2",
		Description: "FOR UNIT TESTS",
	}

	tests := []mocks.DBHttpTest{
		{
			Name:             "No data",
			Request:          th.MakeTestRequest(http.MethodPut, "http://example.com/apitoken", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"Token required. Roles required. Description required","error":"Bad Request"}`,
		},
		{
			Name: "Missing PK",
			Request: th.MakeTestRequest(http.MethodPut, "http://example.com/apitoken", common.APIToken{
				Roles:       "TESTROLES1,TESTROLES2",
				Description: "FOR UNIT TESTS",
			}),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"Token required","error":"Bad Request"}`,
		},
		{
			Name:             "Good data",
			Request:          th.MakeTestRequest(http.MethodPut, "http://example.com/apitoken", validData),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"token":"TESTTOKEN","roles":"TESTROLES1,TESTROLES2","description":"FOR UNIT TESTS","expires_at":null}`,
		},
		{
			Name:             "Error",
			Request:          th.MakeTestRequest(http.MethodPut, "http://example.com/apitoken", 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.HandleAPITokenUpdate, &mock)
}
