// Copyright Earl Warren <contact@earl-warren.org>
// Copyright Loïc Dachary <loic@dachary.org>
// SPDX-License-Identifier: MIT

package f3

import (
	"context"
	"testing"

	filesystem_options "code.forgejo.org/f3/gof3/v3/forges/filesystem/options"
	"code.forgejo.org/f3/gof3/v3/options"
	"code.forgejo.org/f3/gof3/v3/path"
	"code.forgejo.org/f3/gof3/v3/tree/generic"
	tests_forge "code.forgejo.org/f3/gof3/v3/tree/tests/f3/forge"

	"github.com/stretchr/testify/assert"
)

func TestF3PullRequest(t *testing.T) {
	ctx := context.Background()

	for _, factory := range tests_forge.GetFactories() {
		testForge := factory()
		t.Run(testForge.GetName(), func(t *testing.T) {
			// testCase.options will t.Skip if the forge instance is not up
			forgeWriteOptions := testForge.NewOptions(t)
			forgeReadOptions := testForge.NewOptions(t)
			forgeReadOptions.(options.URLInterface).SetURL(forgeWriteOptions.(options.URLInterface).GetURL())

			fixtureTree := generic.GetFactory("f3")(ctx, tests_forge.GetFactory(filesystem_options.Name)().NewOptions(t))
			fixtureTree.Trace("======= build fixture")
			TreeBuildPartial(t, "F3PullRequest"+testForge.GetName(), testForge.GetKindExceptions(), forgeWriteOptions, fixtureTree)

			// craft a PR condition depending on testCase

			fixtureTree.Trace("======= mirror fixture to forge")

			forgeWriteTree := generic.GetFactory("f3")(ctx, forgeWriteOptions)
			generic.TreeMirror(ctx, fixtureTree, forgeWriteTree, generic.NewPathFromString(""), generic.NewMirrorOptions())

			paths := []string{"/forge/users/10111/projects/74823/repositories", "/forge/users/10111/projects/74823/pull_requests"}
			pathPairs := make([][2]path.Path, 0, 5)
			for _, p := range paths {
				p := generic.NewPathFromString(p)
				pathPairs = append(pathPairs, [2]path.Path{p, generic.TreePathRemap(ctx, fixtureTree, p, forgeWriteTree)})
			}

			fixtureTree.Trace("======= read from forge")

			forgeReadTree := generic.GetFactory("f3")(ctx, forgeReadOptions)
			forgeReadTree.WalkAndGet(ctx, generic.NewWalkOptions(nil))

			fixtureTree.Trace("======= mirror forge to filesystem")

			verificationTree := generic.GetFactory("f3")(ctx, tests_forge.GetFactory(filesystem_options.Name)().NewOptions(t))

			for _, pathPair := range pathPairs {
				generic.TreeMirror(ctx, forgeReadTree, verificationTree, pathPair[1], generic.NewMirrorOptions())
			}

			fixtureTree.Trace("======= compare fixture with forge mirrored to filesystem")
			for _, pathPair := range pathPairs {
				fixtureTree.Trace("======= compare %s with %s", pathPair[0], pathPair[1])
				assert.True(t, generic.TreeCompare(ctx, fixtureTree, pathPair[0], verificationTree, pathPair[1]))
			}

			TreeDelete(t, testForge.GetNonTestUsers(), forgeWriteOptions, forgeWriteTree)
		})
	}
}
