package websocket

import (
	"net/http"
	"testing"

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

func TestVerifyTokenAuthorized(t *testing.T) {
	c := mock.Client{
		DoFunc: func(*http.Request) (*http.Response, error) {
			return &http.Response{StatusCode: 200}, nil
		},
	}
	httpclient.Client = &c

	ad := AuthData{
		Token: "validtoken",
	}

	ok, err := verifyToken(ad)
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestVerifyTokenAuthorized", nil, err)
	}
	if !ok {
		t.Errorf(testhelper.TestErrorTemplate, "TestVerifyTokenAuthorized", true, ok)
	}
}

func TestVerifyTokenUnauthorized(t *testing.T) {
	c := mock.Client{
		DoFunc: func(*http.Request) (*http.Response, error) {
			return &http.Response{StatusCode: 401}, nil
		},
	}
	httpclient.Client = &c

	ad := AuthData{
		Token: "invalidtoken",
	}

	ok, err := verifyToken(ad)
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestVerifyTokenUnauthorized", nil, err)
	}
	if ok {
		t.Errorf(testhelper.TestErrorTemplate, "TestVerifyTokenUnauthorized", false, ok)
	}
}

func TestAuthenticateRequest(t *testing.T) {
	c := mock.Client{
		DoFunc: func(*http.Request) (*http.Response, error) {
			return &http.Response{StatusCode: 200}, nil
		},
	}
	httpclient.Client = &c

	ae := AuthEvent{
		Topic: "auth_service",
		Key:   "FISKER123",
		Payload: AuthPayload{
			Handler: "verify",
			Data: AuthData{
				Token: "validtoken",
			},
		},
	}

	ok, err := AuthenticateRequest(ae)
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestAuthenticateRequest", nil, err)
	}
	if !ok {
		t.Errorf(testhelper.TestErrorTemplate, "TestAuthenticateRequest", true, ok)
	}
}

func TestAuthenticateRequestInvalid(t *testing.T) {
	c := mock.Client{
		DoFunc: func(*http.Request) (*http.Response, error) {
			return &http.Response{StatusCode: 401}, nil
		},
	}
	httpclient.Client = &c

	ae := AuthEvent{
		Topic: "invalid_topic",
		Key:   "FISKER123",
		Payload: AuthPayload{
			Handler: "verify",
			Data: AuthData{
				Token: "validtoken",
			},
		},
	}

	_, err := AuthenticateRequest(ae)
	if err == nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestAuthenticateRequestInvalid", "error", nil)
	}
}
