// Copyright F3 Authors
// SPDX-License-Identifier: MIT

package forgejo

import (
	"testing"

	"code.forgejo.org/f3/gof3/v3/tree/generic"

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

func WhiteTestsForgesForgejoOrganizationsMapFetch(t *testing.T, orgs generic.NodeInterface, existingOrgs []generic.NodeInterface) {
	t.Helper()

	ctx := t.Context()

	// organization exists and is fetched
	organizations := orgs.GetDriver().(*organizations)
	for _, org := range existingOrgs {
		require.Empty(t, organizations.nameFromID.Get(org.GetID().Int64()))
		assert.Equal(t, org.GetName(), organizations.getNameFromID(ctx, org.GetID().Int64()))
		assert.NotEmpty(t, organizations.nameFromID.Get(org.GetID().Int64()))
	}

	// organizations does not exist
	assert.Empty(t, organizations.getNameFromID(ctx, 1234))

	// the mapping is cached and the name can be obtained without
	// fetching
	client := organizations.getTreeDriver().client
	defer func() {
		organizations.getTreeDriver().client = client
	}()
	organizations.getTreeDriver().client = nil
	for _, org := range orgs.GetNodeChildren() {
		assert.Equal(t, org.GetName(), organizations.getNameFromID(ctx, org.GetID().Int64()))
	}
}

func WhiteTestsForgesForgejoOrganizationsMapAlreadyPresent(t *testing.T, orgs generic.NodeInterface) {
	t.Helper()

	ctx := t.Context()

	// organization exists and does not need to be fetched
	organizations := orgs.GetDriver().(*organizations)
	for _, org := range orgs.GetNodeChildren() {
		require.Empty(t, organizations.nameFromID.Get(org.GetID().Int64()))
		assert.Equal(t, org.GetName(), organizations.getNameFromID(ctx, org.GetID().Int64()))
		assert.NotEmpty(t, organizations.nameFromID.Get(org.GetID().Int64()))
	}
}
