package usecase_test

import (
	"context"
	"path/filepath"
	"testing"
	"testing/fstest"

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

	"source.toby3d.me/toby3d/home/internal/domain"
	entryfsrepo "source.toby3d.me/toby3d/home/internal/entry/repository/fs"
	"source.toby3d.me/toby3d/home/internal/entry/usecase"
	resourcedummyrepo "source.toby3d.me/toby3d/home/internal/resource/repository/dummy"
)

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

	pages := entryfsrepo.NewFileSystemPageRepository(fstest.MapFS{
		filepath.Join("both", "index.md"):       &fstest.MapFile{Data: []byte(`both/index.md`)},
		filepath.Join("both.md"):                &fstest.MapFile{Data: []byte(`both.md`)},
		filepath.Join("file.md"):                &fstest.MapFile{Data: []byte(`file.md`)},
		filepath.Join("folder", "index.md"):     &fstest.MapFile{Data: []byte(`folder/index.md`)},
		filepath.Join("foo", "bar", "index.md"): &fstest.MapFile{Data: []byte(`foo/bar/index.md`)},
		filepath.Join("foo", "bar.md"):          &fstest.MapFile{Data: []byte(`foo/bar.md`)},
		filepath.Join("index.md"):               &fstest.MapFile{Data: []byte(`index.md`)},
	})

	ucase := usecase.NewEntryUseCase(pages, resourcedummyrepo.NewDummyResourceRepository())

	for name, tc := range map[string]struct {
		input  string
		expect []byte
	}{
		"root":             {"/", []byte(`index.md`)},
		"index":            {"/index", []byte(`index.md`)},
		"index-ext":        {"/index.html", []byte(`index.md`)},
		"file":             {"/file", []byte(`file.md`)},
		"file-slash":       {"/file/", []byte(`file.md`)},
		"file-ext":         {"/file.html", []byte(`file.md`)},
		"both-ext":         {"/both.html", []byte(`both.md`)},
		"folder":           {"/folder", []byte(`folder/index.md`)},
		"folder-slash":     {"/folder/", []byte(`folder/index.md`)},
		"folder-index":     {"/folder/index", []byte(`folder/index.md`)},
		"folder-ext":       {"/folder/index.html", []byte(`folder/index.md`)},
		"both":             {"/both", []byte(`both/index.md`)},
		"both-slash":       {"/both/", []byte(`both/index.md`)},
		"both-index":       {"/both/index", []byte(`both/index.md`)},
		"both-index-ext":   {"/both/index.html", []byte(`both/index.md`)},
		"sub-folder-index": {"/foo/bar/index", []byte(`foo/bar/index.md`)},
		"sub-folder-ext":   {"/foo/bar/index.html", []byte(`foo/bar/index.md`)},
		"sub-folder-slash": {"/foo/bar/", []byte(`foo/bar/index.md`)},
	} {
		name, tc := name, tc

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

			actual, err := ucase.Do(context.Background(), domain.LanguageUnd, tc.input)
			if err != nil {
				t.Fatal(err)
			}

			if diff := cmp.Diff(string(actual.Content), string(tc.expect)); diff != "" {
				t.Error(diff)
			}
		})
	}
}
