package http_test

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/google/go-cmp/cmp"

	"source.toby3d.me/toby3d/home/internal/common"
	"source.toby3d.me/toby3d/home/internal/domain"
	sitestubrepo "source.toby3d.me/toby3d/home/internal/site/repository/stub"
	"source.toby3d.me/toby3d/home/internal/testutil"
	delivery "source.toby3d.me/toby3d/home/internal/webfinger/delivery/http"
	webfingerucase "source.toby3d.me/toby3d/home/internal/webfinger/usecase"
)

func TestHandler_ServeHTTP(t *testing.T) {
	t.Parallel()

	testSite := domain.TestSite(t)
	u := testSite.BaseURL.JoinPath(".well-known", "webfinger")
	u.RawQuery = "resource=acct:user@" + testSite.BaseURL.Hostname()

	req := httptest.NewRequest(http.MethodGet, u.String(), nil)
	req.Header.Set(common.HeaderAccept, common.MIMEApplicationJRDKJSON+", "+common.MIMEApplicationJSON)
	w := httptest.NewRecorder()

	delivery.NewHandler(webfingerucase.NewWebFingerUseCase(sitestubrepo.NewStubSiteRepository(testSite, nil))).
		ServeHTTP(w, req)
	testutil.GoldenEqual(t, w.Result().Body)
}

func TestParseResource(t *testing.T) {
	t.Parallel()

	for name, tc := range map[string]struct {
		input  string
		expect delivery.Resource
	}{
		"profile": {"acct:user@example.com", delivery.Resource{"user", "example.com", false}},
		"email":   {"user@example.com", delivery.Resource{"user", "example.com", true}},
	} {
		name, tc := name, tc

		t.Run(name, func(t *testing.T) {
			t.Parallel()

			result, err := delivery.ParseResource(tc.input)
			if err != nil {
				t.Fatal(err)
			}

			if diff := cmp.Diff(tc.expect, *result); diff != "" {
				t.Error(diff)
			}
		})
	}
}
