package routes

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync"
	"testing"
	"time"

	"bitbucket.org/imediabrands/oos-service/internal/cms"
)

// fakeWarmCMS serves one site, "a.com", with one category of total articles,
// plus a category of "other.com", and counts the requests per action and id.
func fakeWarmCMS(t *testing.T, total int) (calls func(action, id string) int, failArticles func(bool)) {
	t.Helper()
	var mu sync.Mutex
	counts := map[string]int{}
	fail := false

	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		q := r.URL.Query()
		action := q.Get("action")
		mu.Lock()
		counts[action+":"+q.Get("id")+q.Get("cat_id")]++
		failing := fail
		mu.Unlock()

		switch action {
		case "getcategories":
			fmt.Fprint(w, `{"data":{" a.com":[{"cat_id":"1","cat_name":"One"}],"other.com":[{"cat_id":"2","cat_name":"Two"}]}}`)
		case "getcategoryarticles":
			list := ""
			for i := 1; i <= total; i++ {
				if i > 1 {
					list += ","
				}
				list += fmt.Sprintf(`{"id":"%d","title":"Article %d"}`, i, i)
			}
			fmt.Fprintf(w, `{"data":[%s]}`, list)
		case "getarticledata":
			if failing {
				w.WriteHeader(http.StatusBadGateway)
				return
			}
			fmt.Fprintf(w, `{"data":{"id":"%s","content":"<p>body</p>"}}`, q.Get("id"))
		}
	}))
	t.Cleanup(server.Close)

	orig := cmsService
	cmsService = cms.NewService(server.URL, "test-key", time.Hour)
	t.Cleanup(func() { cmsService = orig })

	calls = func(action, id string) int {
		mu.Lock()
		defer mu.Unlock()
		return counts[action+":"+id]
	}
	failArticles = func(v bool) {
		mu.Lock()
		defer mu.Unlock()
		fail = v
	}
	return calls, failArticles
}

func TestWarmCMSCacheFillsListingsAndNewestArticles(t *testing.T) {
	calls, _ := fakeWarmCMS(t, cmsWarmArticlesPerSite+3)

	warmCMSCache([]string{"a.com", "notincms.com"})

	if got := calls("getcategoryarticles", "1"); got != 1 {
		t.Errorf("category of a.com fetched %d times, want 1", got)
	}
	if got := calls("getcategoryarticles", "2"); got != 0 {
		t.Errorf("category of a site not passed in fetched %d times, want 0", got)
	}
	newest := fmt.Sprint(cmsWarmArticlesPerSite + 3)
	if got := calls("getarticledata", newest); got != 1 {
		t.Errorf("newest article fetched %d times, want 1", got)
	}
	if got := calls("getarticledata", "3"); got != 0 {
		t.Errorf("article past the per-site limit fetched %d times, want 0", got)
	}

	// A visitor's requests are now cache hits.
	if _, err := cmsService.GetCategories(); err != nil {
		t.Fatal(err)
	}
	if _, err := cmsService.GetCategoryArticles("1"); err != nil {
		t.Fatal(err)
	}
	if _, err := cmsService.GetArticle(newest); err != nil {
		t.Fatal(err)
	}
	if calls("getcategories", "") != 1 || calls("getcategoryarticles", "1") != 1 || calls("getarticledata", newest) != 1 {
		t.Error("requests after warming went to the CMS instead of the cache")
	}
}

func TestWarmCMSCacheRefreshReplacesEntriesAndKeepsThemOnFailure(t *testing.T) {
	calls, failArticles := fakeWarmCMS(t, 1)

	warmCMSCache([]string{"a.com"})
	warmCMSCache([]string{"a.com"})
	if got := calls("getarticledata", "1"); got != 2 {
		t.Fatalf("article fetched %d times over two passes, want 2", got)
	}

	failArticles(true)
	warmCMSCache([]string{"a.com"})
	if got := calls("getarticledata", "1"); got != 3 {
		t.Fatalf("article fetched %d times, want 3", got)
	}
	data, err := cmsService.GetArticle("1")
	if err != nil || len(data) == 0 {
		t.Errorf("a failed refresh should keep the cached article, got %q, %v", data, err)
	}
	if got := calls("getarticledata", "1"); got != 3 {
		t.Errorf("GetArticle after a failed refresh went to the CMS (%d calls)", got)
	}
}

func TestWarmCMSCacheReportsWhetherThePassStarted(t *testing.T) {
	fakeWarmCMS(t, 1)
	if !warmCMSCache([]string{"a.com"}) {
		t.Error("a full pass returned false")
	}

	failing := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusBadGateway)
	}))
	defer failing.Close()
	cmsService = cms.NewService(failing.URL, "test-key", time.Hour)
	if warmCMSCache([]string{"a.com"}) {
		t.Error("a pass without categories returned true")
	}

	// A nil service makes the pass panic.
	cmsService = nil
	if warmCMSCache([]string{"a.com"}) {
		t.Error("a pass that panicked returned true")
	}
}

func TestLogWarmPanicKeepsTheOtherItemsRunning(t *testing.T) {
	var mu sync.Mutex
	seen := map[string]bool{}
	forEachConcurrently([]string{"a", "b", "c"}, 2, func(item string) {
		defer logWarmPanic(item)
		if item == "b" {
			panic("odd article")
		}
		mu.Lock()
		seen[item] = true
		mu.Unlock()
	})
	if !seen["a"] || !seen["c"] {
		t.Errorf("items after the panic didn't run: %v", seen)
	}
}

func TestForEachConcurrentlyRunsEveryItemOnce(t *testing.T) {
	var mu sync.Mutex
	seen := map[string]int{}
	forEachConcurrently([]string{"a", "b", "c", "d", "e"}, 2, func(item string) {
		mu.Lock()
		seen[item]++
		mu.Unlock()
	})
	if len(seen) != 5 {
		t.Fatalf("ran %d items, want 5", len(seen))
	}
	for item, n := range seen {
		if n != 1 {
			t.Errorf("%s ran %d times", item, n)
		}
	}
	forEachConcurrently(nil, 2, func(string) { t.Error("ran on no items") })
}
