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

func TestAPITokenAdd(t *testing.T) {
	mock := mo.MockAPITokens{}
	services.GetDB().SetAPITokens(&mock)
	validData := common.APIToken{
		Token:       "TESTTOKEN",
		Roles:       "TESTROLES1,TESTROLES2",
		Description: "FOR UNIT TESTS",
	}
	tests := []mo.DBHttpTest{
		{
			Name:             "No data",
			Request:          th.MakeTestRequest(http.MethodPost, "http://example.com/apitoken", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"Token required. Roles required. Description required","error":"Bad Request"}`,
		},
		{
			Name: "Invalid data",
			Request: th.MakeTestRequest(http.MethodPost, "http://example.com/apitoken", common.APIToken{
				Token: "TESTTOKEN",
			}),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"Roles required. Description required","error":"Bad Request"}`,
		},
		{
			Name:             "Valid data",
			Request:          th.MakeTestRequest(http.MethodPost, "http://example.com/apitoken", validData),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"token":"TESTTOKEN","roles":"TESTROLES1,TESTROLES2","description":"FOR UNIT TESTS","expires_at":null}`,
		},
		{
			Name:             "DB error",
			Request:          th.MakeTestRequest(http.MethodPost, "http://example.com/apitoken", 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.HandleAPITokenAdd, &mock)
}
