package usecase

import (
	"encoding/json"
	"os"
	"path/filepath"
	"testing"

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

type qualityFixture struct {
	ID     string             `json:"id"`
	Intent string             `json:"intent"`
	Terms  []string           `json:"terms"`
	Target int                `json:"target"`
	Cases  []qualityCandidate `json:"cases"`
}

type qualityCandidate struct {
	URL      string `json:"url"`
	Text     string `json:"text"`
	Relevant bool   `json:"relevant"`
}

func loadQualityFixtures(t *testing.T) []qualityFixture {
	t.Helper()
	raw, err := os.ReadFile(filepath.Join("testdata", "topic_quality_cases.json"))
	require.NoError(t, err)
	var fixtures []qualityFixture
	require.NoError(t, json.Unmarshal(raw, &fixtures))
	require.NotEmpty(t, fixtures)
	return fixtures
}

func TestQualityFixturesCoverRepresentativeIntentSignals(t *testing.T) {
	fixtures := loadQualityFixtures(t)
	require.GreaterOrEqual(t, len(fixtures), 4)

	for _, fixture := range fixtures {
		require.NotEmpty(t, fixture.ID)
		require.NotEmpty(t, fixture.Intent)
		require.NotEmpty(t, fixture.Terms)
		require.NotEmpty(t, fixture.Cases)

		for _, candidate := range fixture.Cases {
			require.NotEmpty(t, candidate.URL, fixture.ID)
			require.NotEmpty(t, candidate.Text, fixture.ID)
			got := textMatchesSearchTerm(candidate.Text, fixture.Terms[0])
			require.Equal(t, candidate.Relevant, got, "%s candidate=%q", fixture.ID, candidate.Text)
		}
	}
}

func TestQualityFixturesCanonicalizeAliasWithoutHostnameDuplicates(t *testing.T) {
	fixtures := loadQualityFixtures(t)
	var alias *qualityFixture
	for i := range fixtures {
		if fixtures[i].ID == "alias-shortcode" {
			alias = &fixtures[i]
			break
		}
	}
	require.NotNil(t, alias)
	require.Len(t, alias.Cases, 2)
	require.Equal(t, canonicalPostIdentity(alias.Cases[0].URL), canonicalPostIdentity(alias.Cases[1].URL))
	require.Equal(t, "threads-post:SameCode", canonicalPostIdentity(alias.Cases[0].URL))
}
