package usecase

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

func TestCrawlerProviderKeepsOldPublishedPosts(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		_, _ = w.Write([]byte(`{"posts":[{"permalink":"https://www.threads.net/@a/post/old","text":"市集舊文","published_at":"2020-01-02T00:00:00Z"}]}`))
	}))
	defer server.Close()

	provider := NewHTTPCrawlerProvider(server.URL, "token")
	provider.HTTP = server.Client()
	got, err := provider.SearchChrome(context.Background(), "{}", []string{"市集"}, 1)
	if err != nil {
		t.Fatal(err)
	}
	if len(got) != 1 || got[0].PublishedAt == 0 {
		t.Fatalf("old crawler result=%+v", got)
	}
}

func TestPublishedTimeOnlyAffectsScore(t *testing.T) {
	now := time.Now().UTC()
	fresh := now.Add(-10 * 24 * time.Hour).UnixNano()
	mid := now.Add(-60 * 24 * time.Hour).UnixNano()
	if !isSoftAged(mid, defaultScoutSoftAgeDays) {
		t.Fatal("60d should be soft-aged at 45d")
	}
	if isSoftAged(fresh, defaultScoutSoftAgeDays) {
		t.Fatal("10d should not be soft-aged")
	}
	if isSoftAged(0, defaultScoutSoftAgeDays) {
		t.Fatal("unknown time is not soft-aged")
	}
	// There is intentionally no hard date cutoff anymore; even very old
	// candidates reach relevance/classification and are ordered by score.
}

func TestNormalizeSearchTrack(t *testing.T) {
	if normalizeSearchTrack("both") != "both" {
		t.Fatal("both")
	}
	if normalizeSearchTrack("recent") != "recent" {
		t.Fatal("recent")
	}
	if normalizeSearchTrack("TOP") != "top" {
		t.Fatal("top")
	}
}

func TestSortHitsByTrackAndPostedAt(t *testing.T) {
	hits := []ThreadSearchResult{
		{URL: "a", Track: "top", PublishedAt: 300},
		{URL: "b", Track: "both", PublishedAt: 100},
		{URL: "c", Track: "recent", PublishedAt: 200},
	}
	sortHitsByTrackAndPostedAt(hits)
	if hits[0].Track != "both" {
		t.Fatalf("first=%s want both", hits[0].Track)
	}
	if hits[1].Track != "recent" {
		t.Fatalf("second=%s want recent", hits[1].Track)
	}
}
