package auth_test

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"testing"

	auth "github.com/fiskerinc/cloud-services/pkg/auth"
	"github.com/fiskerinc/cloud-services/pkg/httpclient"
	"github.com/fiskerinc/cloud-services/pkg/httpclient/mock"
	"github.com/fiskerinc/cloud-services/pkg/testhelper"
)

const responseUserConsentJSON = `{"access_token":"eyJraWQiOiJqSXowUVRjc0tDVCtoeEd6MlMwK0NoUHlON3c4cmlQXC9sNm1xekFYUmw2bz0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIyZGQ2ZmVkOS1lNTgyLTQ1MWItYTkzYi01Yjk0MTBkZmJjNDMiLCJjb2duaXRvOmdyb3VwcyI6WyJ1cy13ZXN0LTJfQVd3akxYeW0yX0F6dXJlQUQiXSwidG9rZW5fdXNlIjoiYWNjZXNzIiwic2NvcGUiOiJodHRwczpcL1wvZmlza2VyaW5jLmNvbVwvb3RhdXBkYXRlLnJlYWQgaHR0cHM6XC9cL2Zpc2tlcmluYy5jb21cL290YXVwZGF0ZS5jcmVhdGUgb3BlbmlkIGVtYWlsIiwiYXV0aF90aW1lIjoxNjEzNjA3NTc2LCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAudXMtd2VzdC0yLmFtYXpvbmF3cy5jb21cL3VzLXdlc3QtMl9BV3dqTFh5bTIiLCJleHAiOjE2MTM2MTExNzYsImlhdCI6MTYxMzYwNzU3NiwidmVyc2lvbiI6MiwianRpIjoiYzUyNjI0YjItYmJkYi00N2RiLTllNTgtOGU5ZmU3Yjg1ODMxIiwiY2xpZW50X2lkIjoiN2NrMnRmb3FhdmM3MmM0NWhoN3RnZTQya2QiLCJ1c2VybmFtZSI6ImF6dXJlYWRfand1QGZpc2tlcmluYy5jb20ifQ.FvlES5AgjhymQKnHP41D2Ude0Ten6L8REBRXTyu5dyWGrG4vTfBGoxlkGE2-MEFc0s6uhbdST_E2Mc5QNlXG47ibK14tFl6kOqDd74TCfg5sWghb_nSjC-M769eUHQSQcs4L8jcn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qD-go4jqDR_ie3aGc5Fm8Vd6lSh_2HW2GR0Ht0ASoCbl3C5roXCRkyTTaGl3nX6uwfg.thw4B0ug4OIZsZrDzCtJcQ","expires_in": 3600,"token_type": "Bearer"}`

func TestHandleUserConsentToken(t *testing.T) {
	setupUserConsentMockAuthClient()

	authResp, err := auth.RequestUserConsentToken()
	if err != nil {
		t.Errorf("should not return an error")
	}

	const someValueCondition = "Some value"

	if len(authResp.AccessToken.JWTToken) == 0 {
		t.Errorf(testhelper.TestErrorTemplate, "Access token", someValueCondition, authResp.AccessToken.JWTToken)
	}

	if len(authResp.IDToken.JWTToken) == 0 {
		t.Errorf(testhelper.TestErrorTemplate, "ID token", someValueCondition, authResp.IDToken.JWTToken)
	}

	if len(authResp.RefreshToken.Token) == 0 {
		t.Errorf(testhelper.TestErrorTemplate, "Refresh token", someValueCondition, authResp.RefreshToken.Token)
	}

	token, err := auth.CognitoUserConsentJWT.GetUserConsentToken()
	if err != nil {
		t.Errorf(err.Error())
	}
	if token != authResp.AccessToken.JWTToken {
		t.Errorf(testhelper.TestErrorTemplate, "Access token", someValueCondition, authResp.AccessToken.JWTToken)
	}
}

func setupUserConsentMockAuthClient() {
	httpclient.Client = &mock.Client{
		DoFunc: func(r *http.Request) (*http.Response, error) {
			return &http.Response{
				Body: ioutil.NopCloser(bytes.NewBufferString(responseUserConsentJSON)),
			}, nil

		},
	}
}
