package handlers_test

import (
	"net/http"
	"testing"

	"github.com/fiskerinc/cloud-services/pkg/httpclient/tester"
	"github.com/fiskerinc/cloud-services/pkg/redis"
	th "github.com/fiskerinc/cloud-services/pkg/testhelper"
	"github.com/pkg/errors"
	"otaupdate/handlers"
)

var someErr = errors.New("some err")

func TestHandleDashboardToken(t *testing.T) {
	tests := map[string]struct {
		mockGetAccessToken func(r redis.Client) (string, error)
		mockGetGuestToken  func(r redis.Client, accToken string) (string, error)
		http               tester.HttpTestCase
	}{
		"success": {
			mockGetAccessToken: successGetAccessToken,
			mockGetGuestToken:  successGetGuestToken,
			http: tester.HttpTestCase{
				Request:          th.MakeTestRequest(http.MethodGet, "", nil),
				ExpectedStatus:   http.StatusOK,
				ExpectedResponse: `{"token":"valid_token"}`,
			},
		},
		"fail_get_access": {
			mockGetAccessToken: failGetAccessToken,
			http: tester.HttpTestCase{
				Request:          th.MakeTestRequest(http.MethodGet, "", nil),
				ExpectedStatus:   http.StatusServiceUnavailable,
				ExpectedResponse: `{"message":"some err","error":"Service Unavailable"}`,
			},
		},
		"fail_get_guest": {
			mockGetAccessToken: successGetAccessToken,
			mockGetGuestToken:  failGetGuestToken,
			http: tester.HttpTestCase{
				Request:          th.MakeTestRequest(http.MethodGet, "", nil),
				ExpectedStatus:   http.StatusServiceUnavailable,
				ExpectedResponse: `{"message":"some err","error":"Service Unavailable"}`,
			},
		},
	}
	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			handlers.SetGetAccessTokenFunc(tt.mockGetAccessToken)
			handlers.SetGetGuestTokenFunc(tt.mockGetGuestToken)
			w := tt.http.Test(handlers.HandleDashboardToken)

			tt.http.ValidateHttp(t, name, w)
		})
	}
}

func successGetAccessToken(r redis.Client) (string, error) {
	return "", nil
}
func failGetAccessToken(r redis.Client) (string, error) {
	return "", someErr
}

func successGetGuestToken(r redis.Client, accToken string) (string, error) {
	return "valid_token", nil
}
func failGetGuestToken(r redis.Client, accToken string) (string, error) {
	return "", someErr
}
