package routes

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"bitbucket.org/imediabrands/oos-service/internal/cms"
	"bitbucket.org/imediabrands/oos-service/middlewares"
	"github.com/spf13/viper"
)

// ---------------------------------------------------------------------------
// Mock CMS server
// ---------------------------------------------------------------------------

// mockCMSData holds the data the fake CMS server will return per action.
type mockCMSData struct {
	// categories is returned for action=getcategories
	categories map[string]interface{}
	// articlesByCategory maps cat_id → article list returned for
	// action=getcategoryarticles
	articlesByCategory map[string][]map[string]interface{}
	// forceError, when true, returns HTTP 500 for every request
	forceError bool
}

// newMockCMSServer creates an httptest.Server that mimics the CMS API used by
// GetCategories and GetCategoryArticles. The server dispatches on the
// "action" query parameter exactly as the real CMS does.
func newMockCMSServer(t *testing.T, d mockCMSData) *httptest.Server {
	t.Helper()
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if d.forceError {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		action := r.URL.Query().Get("action")
		w.Header().Set("Content-Type", "application/json")

		switch action {
		case "getcategories":
			json.NewEncoder(w).Encode(d.categories)

		case "getcategoryarticles":
			catID := r.URL.Query().Get("cat_id")
			articles, ok := d.articlesByCategory[catID]
			if !ok {
				json.NewEncoder(w).Encode(map[string]interface{}{"data": []interface{}{}})
				return
			}
			asInterface := make([]interface{}, len(articles))
			for i, a := range articles {
				asInterface[i] = a
			}
			json.NewEncoder(w).Encode(map[string]interface{}{"data": asInterface})

		default:
			w.WriteHeader(http.StatusBadRequest)
		}
	}))
	return srv
}

// withCMSService swaps the package-level cmsService for the duration of a
// test and returns a teardown function that restores the original and closes
// the test server.
func withCMSService(t *testing.T, srv *httptest.Server) func() {
	t.Helper()
	orig := cmsService
	cmsService = cms.NewService(srv.URL, "test-key", time.Minute)
	return func() {
		cmsService = orig
		srv.Close()
	}
}

// ---------------------------------------------------------------------------
// Request helper
// ---------------------------------------------------------------------------

// requestArticles fires a GET against DataArticlesHandler.
// The domain is passed via the Host header, matching how DataCategoriesHandler
// resolves the domain (through extractDomain).
func requestArticles(t *testing.T, domain, rawQuery string) *httptest.ResponseRecorder {
	t.Helper()
	target := "/data/articles"
	if rawQuery != "" {
		target += "?" + rawQuery
	}
	req := httptest.NewRequest(http.MethodGet, target, nil)
	req.Host = domain
	rr := httptest.NewRecorder()
	DataArticlesHandler().ServeHTTP(rr, req)
	return rr
}

// ---------------------------------------------------------------------------
// Decode helpers
// ---------------------------------------------------------------------------

func decodeBody(t *testing.T, rr *httptest.ResponseRecorder) map[string]interface{} {
	t.Helper()
	var body map[string]interface{}
	if err := json.NewDecoder(rr.Body).Decode(&body); err != nil {
		t.Fatalf("decode response body: %v", err)
	}
	return body
}

func dataSlice(t *testing.T, body map[string]interface{}) []interface{} {
	t.Helper()
	d, ok := body["data"].([]interface{})
	if !ok {
		t.Fatalf("expected body[\"data\"] to be []interface{}, got %T", body["data"])
	}
	return d
}

func paginationMap(t *testing.T, body map[string]interface{}) map[string]interface{} {
	t.Helper()
	p, ok := body["pagination"].(map[string]interface{})
	if !ok {
		t.Fatalf("expected body[\"pagination\"] to be map[string]interface{}, got %T", body["pagination"])
	}
	return p
}

// ---------------------------------------------------------------------------
// Shared test fixtures
// ---------------------------------------------------------------------------

// twoCategories is a categories response with two categories for "example.com".
var twoCategories = map[string]interface{}{
	"data": map[string]interface{}{
		"example.com": []interface{}{
			map[string]interface{}{"cat_id": "cat1", "name": "Nature"},
			map[string]interface{}{"cat_id": "cat2", "name": "Science"},
		},
	},
}

// articlesByCat maps cat_id → articles served by the mock CMS.
// cat1 has 3 articles, cat2 has 2 articles (id=3 overlaps with cat1 to test dedup).
var articlesByCat = map[string][]map[string]interface{}{
	"cat1": {
		{"id": "1", "title": "Climate Change Overview", "content": "An overview of climate change.", "publish_date": "2024-03-15"},
		{"id": "2", "title": "Ocean Temperatures Rising", "content": "Oceans are getting warmer due to climate.", "publish_date": "2024-01-10"},
		{"id": "3", "title": "Renewable Energy Trends", "content": "Solar and wind power are growing fast.", "publish_date": "2024-05-20"},
	},
	"cat2": {
		{"id": "3", "title": "Renewable Energy Trends", "content": "Solar and wind power are growing fast.", "publish_date": "2024-05-20"}, // duplicate of cat1
		{"id": "4", "title": "Arctic Ice Melting", "content": "The arctic is losing ice at record pace.", "publish_date": "2023-11-05"},
		{"id": "5", "title": "Carbon Capture Tech", "content": "New technology captures carbon from air.", "publish_date": "2024-02-28"},
	},
}

// totalUniqueArticles is 5 (id=3 shared across both categories).
const totalUniqueArticles = 5

func defaultMock(t *testing.T) func() {
	srv := newMockCMSServer(t, mockCMSData{
		categories:         twoCategories,
		articlesByCategory: articlesByCat,
	})
	return withCMSService(t, srv)
}

// ---------------------------------------------------------------------------
// Handler-level tests
// ---------------------------------------------------------------------------

func TestDataArticlesHandler_BasicListing(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "limit=20")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rr.Code)
	}
	body := decodeBody(t, rr)
	data := dataSlice(t, body)
	if len(data) != totalUniqueArticles {
		t.Errorf("expected %d articles, got %d", totalUniqueArticles, len(data))
	}
	pagination := paginationMap(t, body)
	if int(pagination["total"].(float64)) != totalUniqueArticles {
		t.Errorf("expected pagination.total=%d, got %v", totalUniqueArticles, pagination["total"])
	}
}

func TestDataArticlesHandler_MergesAcrossCategories(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "limit=20")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rr.Code)
	}
	// 3 from cat1 + 3 from cat2, minus 1 duplicate = 5 unique articles.
	body := decodeBody(t, rr)
	data := dataSlice(t, body)
	if len(data) != 5 {
		t.Errorf("expected 5 unique merged articles, got %d", len(data))
	}
}

func TestDataArticlesHandler_DeduplicatesArticles(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "limit=20")

	body := decodeBody(t, rr)
	data := dataSlice(t, body)

	seen := make(map[interface{}]bool)
	for _, item := range data {
		a := item.(map[string]interface{})
		id := a["id"]
		if seen[id] {
			t.Errorf("duplicate article id=%v in merged result", id)
		}
		seen[id] = true
	}
}

func TestDataArticlesHandler_SortRecent(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "sort=recent&limit=20")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rr.Code)
	}
	body := decodeBody(t, rr)
	data := dataSlice(t, body)

	dates := make([]string, len(data))
	for i, item := range data {
		a := item.(map[string]interface{})
		dates[i] = a["publish_date"].(string)
	}
	for i := 1; i < len(dates); i++ {
		if dates[i] > dates[i-1] {
			t.Errorf("not sorted desc: pos %d (%s) > pos %d (%s)", i, dates[i], i-1, dates[i-1])
		}
	}
}

func TestDataArticlesHandler_SearchByTitle(t *testing.T) {
	defer defaultMock(t)()

	// "climate" appears in the title of article 1 and content of article 2.
	rr := requestArticles(t, "example.com", "q=climate&limit=20")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rr.Code)
	}
	body := decodeBody(t, rr)
	data := dataSlice(t, body)
	if len(data) != 2 {
		t.Errorf("expected 2 results for q=climate, got %d", len(data))
	}
}

func TestDataArticlesHandler_SearchByContent(t *testing.T) {
	defer defaultMock(t)()

	// "carbon" only appears in the content of article 5.
	rr := requestArticles(t, "example.com", "q=carbon&limit=20")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rr.Code)
	}
	body := decodeBody(t, rr)
	data := dataSlice(t, body)
	if len(data) != 1 {
		t.Errorf("expected 1 result for q=carbon, got %d", len(data))
	}
	article := data[0].(map[string]interface{})
	if article["id"] != "5" {
		t.Errorf("expected article id=5, got %v", article["id"])
	}
}

func TestDataArticlesHandler_SearchAndSortCombined(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "q=climate&sort=recent&limit=20")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rr.Code)
	}
	body := decodeBody(t, rr)
	data := dataSlice(t, body)
	if len(data) != 2 {
		t.Fatalf("expected 2 climate results, got %d", len(data))
	}
	// Most recent first: 2024-03-15 before 2024-01-10.
	first := data[0].(map[string]interface{})
	second := data[1].(map[string]interface{})
	if first["publish_date"].(string) < second["publish_date"].(string) {
		t.Errorf("expected descending order, got %s then %s",
			first["publish_date"], second["publish_date"])
	}
}

func TestDataArticlesHandler_DomainInPath(t *testing.T) {
	// Two distinct domains, each with its own category and articles.
	twoDomainCategories := map[string]interface{}{
		"data": map[string]interface{}{
			"site-a.com": []interface{}{
				map[string]interface{}{"cat_id": "a1", "name": "A-Cat"},
			},
			"site-b.com": []interface{}{
				map[string]interface{}{"cat_id": "b1", "name": "B-Cat"},
			},
		},
	}
	twoDomainArticles := map[string][]map[string]interface{}{
		"a1": {
			{"id": "100", "title": "Site A article", "content": "A content.", "publish_date": "2024-01-01"},
		},
		"b1": {
			{"id": "200", "title": "Site B article", "content": "B content.", "publish_date": "2024-06-01"},
			{"id": "201", "title": "Site B second", "content": "B content 2.", "publish_date": "2024-06-02"},
		},
	}

	srv := newMockCMSServer(t, mockCMSData{
		categories:         twoDomainCategories,
		articlesByCategory: twoDomainArticles,
	})
	defer withCMSService(t, srv)()

	rr1 := requestArticles(t, "site-a.com", "limit=20")
	rr2 := requestArticles(t, "site-b.com", "limit=20")

	if rr1.Code != http.StatusOK {
		t.Fatalf("site-a.com: expected 200, got %d", rr1.Code)
	}
	if rr2.Code != http.StatusOK {
		t.Fatalf("site-b.com: expected 200, got %d", rr2.Code)
	}

	body1 := decodeBody(t, rr1)
	body2 := decodeBody(t, rr2)
	data1 := dataSlice(t, body1)
	data2 := dataSlice(t, body2)

	// site-a has 1 article; site-b has 2 articles.
	if len(data1) != 1 {
		t.Errorf("site-a.com: expected 1 article, got %d", len(data1))
	}
	if len(data2) != 2 {
		t.Errorf("site-b.com: expected 2 articles, got %d", len(data2))
	}

	// Verify correct article IDs per domain.
	a1ID := data1[0].(map[string]interface{})["id"]
	if a1ID != "100" {
		t.Errorf("site-a.com: expected article id=100, got %v", a1ID)
	}
}

func TestDataArticlesHandler_Pagination(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "page=1&limit=2")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rr.Code)
	}
	body := decodeBody(t, rr)
	data := dataSlice(t, body)
	pagination := paginationMap(t, body)

	if len(data) != 2 {
		t.Errorf("expected 2 articles on page 1, got %d", len(data))
	}
	if int(pagination["total"].(float64)) != totalUniqueArticles {
		t.Errorf("expected total=%d, got %v", totalUniqueArticles, pagination["total"])
	}
	if int(pagination["total_pages"].(float64)) != 3 {
		t.Errorf("expected total_pages=3, got %v", pagination["total_pages"])
	}
	if pagination["has_next"].(bool) != true {
		t.Error("expected has_next=true")
	}
	if pagination["has_prev"].(bool) != false {
		t.Error("expected has_prev=false on page 1")
	}
}

func TestDataArticlesHandler_PaginationPage2(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "page=2&limit=2")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rr.Code)
	}
	body := decodeBody(t, rr)
	data := dataSlice(t, body)
	pagination := paginationMap(t, body)

	if len(data) != 2 {
		t.Errorf("expected 2 articles on page 2, got %d", len(data))
	}
	if pagination["has_prev"].(bool) != true {
		t.Error("expected has_prev=true on page 2")
	}
}

func TestDataArticlesHandler_EmptyResults(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "q=zzznomatch")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200 for empty result set, got %d", rr.Code)
	}
	body := decodeBody(t, rr)
	data := dataSlice(t, body)
	if len(data) != 0 {
		t.Errorf("expected empty data slice, got %d items", len(data))
	}
	pagination := paginationMap(t, body)
	if int(pagination["total"].(float64)) != 0 {
		t.Errorf("expected total=0, got %v", pagination["total"])
	}
}

func TestDataArticlesHandler_PageOutOfRange(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "page=999&limit=10")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200 for out-of-range page, got %d", rr.Code)
	}
	body := decodeBody(t, rr)
	data := dataSlice(t, body)
	if len(data) != 0 {
		t.Errorf("expected empty slice for out-of-range page, got %d", len(data))
	}
}

func TestDataArticlesHandler_InvalidSort(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "sort=invalid")

	if rr.Code != http.StatusBadRequest {
		t.Errorf("expected 400 for invalid sort, got %d", rr.Code)
	}
}

func TestDataArticlesHandler_InvalidPageFallsBackToDefault(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "page=abc&limit=10")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200 for invalid page value, got %d", rr.Code)
	}
	body := decodeBody(t, rr)
	pagination := paginationMap(t, body)
	if int(pagination["page"].(float64)) != 1 {
		t.Errorf("expected page=1 fallback, got %v", pagination["page"])
	}
}

func TestDataArticlesHandler_InvalidLimitFallsBackToDefault(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "limit=notanumber")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200 for invalid limit value, got %d", rr.Code)
	}
	body := decodeBody(t, rr)
	pagination := paginationMap(t, body)
	if int(pagination["limit"].(float64)) != 10 {
		t.Errorf("expected limit=10 fallback, got %v", pagination["limit"])
	}
}

func TestDataArticlesHandler_CMSError(t *testing.T) {
	srv := newMockCMSServer(t, mockCMSData{forceError: true})
	defer withCMSService(t, srv)()

	rr := requestArticles(t, "example.com", "")

	if rr.Code != http.StatusInternalServerError {
		t.Errorf("expected 500 on CMS error, got %d", rr.Code)
	}
}

func TestDataArticlesHandler_CategoryFetchErrorSkipped(t *testing.T) {
	// cat2 will 404 (not in articlesByCategory map), so only cat1 articles
	// are returned. The handler should not error out.
	srv := newMockCMSServer(t, mockCMSData{
		categories: twoCategories,
		articlesByCategory: map[string][]map[string]interface{}{
			"cat1": articlesByCat["cat1"],
			// cat2 intentionally absent → mock returns empty []
		},
	})
	defer withCMSService(t, srv)()

	rr := requestArticles(t, "example.com", "limit=20")

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200 even when one category has no articles, got %d", rr.Code)
	}
	body := decodeBody(t, rr)
	data := dataSlice(t, body)
	if len(data) != 3 {
		t.Errorf("expected 3 articles (cat1 only), got %d", len(data))
	}
}

func TestDataArticlesHandler_ContentTypeIsJSON(t *testing.T) {
	defer defaultMock(t)()

	rr := requestArticles(t, "example.com", "")

	ct := rr.Header().Get("Content-Type")
	if ct != "application/json; charset=utf-8" {
		t.Errorf("expected application/json; charset=utf-8, got %q", ct)
	}
}

// ---------------------------------------------------------------------------
// Unit tests: extractCategoryIDs
// ---------------------------------------------------------------------------

func TestExtractCategoryIDs_DomainKeyed(t *testing.T) {
	response := map[string]interface{}{
		"data": map[string]interface{}{
			"example.com": []interface{}{
				map[string]interface{}{"cat_id": "1", "name": "Fitness"},
				map[string]interface{}{"cat_id": "2", "name": "Health"},
			},
		},
	}
	ids := extractCategoryIDs(response, "example.com")
	if len(ids) != 2 || ids[0] != "1" || ids[1] != "2" {
		t.Errorf("expected [1 2], got %v", ids)
	}
}

func TestExtractCategoryIDs_FallbackWhenNoDomainKey(t *testing.T) {
	response := map[string]interface{}{
		"data": map[string]interface{}{
			"other.com": []interface{}{
				map[string]interface{}{"cat_id": "9", "name": "Other"},
			},
		},
	}
	// domain="example.com" not present → falls back to first []interface{}
	ids := extractCategoryIDs(response, "example.com")
	if len(ids) != 1 || ids[0] != "9" {
		t.Errorf("expected [9] via fallback, got %v", ids)
	}
}

func TestExtractCategoryIDs_UntrimmedDomainKey(t *testing.T) {
	response := map[string]interface{}{
		"data": map[string]interface{}{
			"other.com": []interface{}{
				map[string]interface{}{"cat_id": "9", "name": "Other"},
			},
			" Example.com ": []interface{}{
				map[string]interface{}{"cat_id": "1", "name": "Fitness"},
			},
		},
	}
	// The CMS key has stray spaces and a capital; it must still win over the fallback.
	for i := 0; i < 20; i++ {
		ids := extractCategoryIDs(response, "example.com")
		if len(ids) != 1 || ids[0] != "1" {
			t.Fatalf("expected [1], got %v", ids)
		}
	}
}

func TestExtractCategoryIDs_AlternativeIDFields(t *testing.T) {
	for _, field := range []string{"id", "category_id", "catId"} {
		response := map[string]interface{}{
			"data": map[string]interface{}{
				"example.com": []interface{}{
					map[string]interface{}{field: "42", "name": "Test"},
				},
			},
		}
		ids := extractCategoryIDs(response, "example.com")
		if len(ids) != 1 || ids[0] != "42" {
			t.Errorf("field %q: expected [42], got %v", field, ids)
		}
	}
}

func TestExtractCategoryIDs_InvalidStructure(t *testing.T) {
	response := map[string]interface{}{
		"data": "not-a-map",
	}
	ids := extractCategoryIDs(response, "example.com")
	if len(ids) != 0 {
		t.Errorf("expected nil/empty for invalid structure, got %v", ids)
	}
}

func TestExtractCategoryIDs_EmptyCategories(t *testing.T) {
	response := map[string]interface{}{
		"data": map[string]interface{}{
			"example.com": []interface{}{},
		},
	}
	ids := extractCategoryIDs(response, "example.com")
	if len(ids) != 0 {
		t.Errorf("expected empty, got %v", ids)
	}
}

func TestExtractCategoryIDs_IgnoresSubcategoryIDs(t *testing.T) {
	// Subcategory IDs collide across sites when used as top-level cat_id.
	response := map[string]interface{}{
		"data": map[string]interface{}{
			"pointwines.com": []interface{}{
				map[string]interface{}{
					"cat_id":   "101",
					"cat_name": "Wine 101",
					"subcategories": []interface{}{
						map[string]interface{}{"id": float64(1087), "name": "Wine Types"},
						map[string]interface{}{"id": "1088", "name": "Wine Grapes"},
					},
				},
				map[string]interface{}{"cat_id": "100", "cat_name": "Articles"},
			},
		},
	}
	ids := extractCategoryIDs(response, "pointwines.com")
	if len(ids) != 2 || ids[0] != "101" || ids[1] != "100" {
		t.Errorf("expected top-level IDs only [101 100], got %v", ids)
	}
}

// ---------------------------------------------------------------------------
// Unit tests: filterArticlesByKeyword
// ---------------------------------------------------------------------------

func TestFilterArticlesByKeyword_MatchTitle(t *testing.T) {
	articles := []interface{}{
		map[string]interface{}{"id": "1", "title": "Go Programming", "content": "Learn Go."},
		map[string]interface{}{"id": "2", "title": "Python Basics", "content": "Learn Python."},
	}
	result := filterArticlesByKeyword(articles, "go")
	if len(result) != 1 {
		t.Errorf("expected 1 match, got %d", len(result))
	}
}

func TestFilterArticlesByKeyword_MatchContent(t *testing.T) {
	articles := []interface{}{
		map[string]interface{}{"id": "1", "title": "Programming", "content": "Go is fast."},
		map[string]interface{}{"id": "2", "title": "Scripting", "content": "Python is easy."},
	}
	result := filterArticlesByKeyword(articles, "go is")
	if len(result) != 1 {
		t.Errorf("expected 1 match, got %d", len(result))
	}
	a := result[0].(map[string]interface{})
	if a["id"] != "1" {
		t.Errorf("expected id=1, got %v", a["id"])
	}
}

func TestFilterArticlesByKeyword_CaseInsensitive(t *testing.T) {
	articles := []interface{}{
		map[string]interface{}{"id": "1", "title": "Climate Change", "content": "Global warming."},
	}
	for _, kw := range []string{"climate", "CLIMATE", "Climate"} {
		result := filterArticlesByKeyword(articles, kw)
		if len(result) != 1 {
			t.Errorf("keyword %q: expected 1 match, got %d", kw, len(result))
		}
	}
}

func TestFilterArticlesByKeyword_EmptyKeyword(t *testing.T) {
	articles := []interface{}{
		map[string]interface{}{"id": "1", "title": "Test", "content": "Content."},
	}
	result := filterArticlesByKeyword(articles, "")
	if len(result) != 1 {
		t.Errorf("empty keyword should return all articles, got %d", len(result))
	}
}

func TestFilterArticlesByKeyword_NoMatch(t *testing.T) {
	articles := []interface{}{
		map[string]interface{}{"id": "1", "title": "Tech News", "content": "Latest tech."},
	}
	result := filterArticlesByKeyword(articles, "zzznomatch")
	if len(result) != 0 {
		t.Errorf("expected 0 matches, got %d", len(result))
	}
}

// ---------------------------------------------------------------------------
// Unit tests: sortArticlesByRecent
// ---------------------------------------------------------------------------

func TestSortArticlesByRecent_Order(t *testing.T) {
	articles := []interface{}{
		map[string]interface{}{"id": "1", "publish_date": "2024-01-10"},
		map[string]interface{}{"id": "2", "publish_date": "2024-05-20"},
		map[string]interface{}{"id": "3", "publish_date": "2023-11-05"},
	}
	sorted := sortArticlesByRecent(articles)

	ids := make([]string, len(sorted))
	for i, item := range sorted {
		a := item.(map[string]interface{})
		ids[i] = a["id"].(string)
	}
	want := []string{"2", "1", "3"}
	for i, id := range want {
		if ids[i] != id {
			t.Errorf("position %d: expected id=%s, got %s", i, id, ids[i])
		}
	}
}

func TestSortArticlesByRecent_PreservesOriginalSlice(t *testing.T) {
	articles := []interface{}{
		map[string]interface{}{"id": "1", "publish_date": "2024-01-10"},
		map[string]interface{}{"id": "2", "publish_date": "2024-05-20"},
	}
	originalFirstID := articles[0].(map[string]interface{})["id"]

	sorted := sortArticlesByRecent(articles)

	if articles[0].(map[string]interface{})["id"] != originalFirstID {
		t.Error("sortArticlesByRecent must not mutate the input slice")
	}
	if sorted[0].(map[string]interface{})["id"] == originalFirstID {
		t.Error("sorted slice should start with the most recent article")
	}
}

func TestSortArticlesByRecent_MissingDates(t *testing.T) {
	articles := []interface{}{
		map[string]interface{}{"id": "1", "publish_date": ""},
		map[string]interface{}{"id": "2", "publish_date": "2024-03-15"},
		map[string]interface{}{"id": "3", "publish_date": ""},
	}
	sorted := sortArticlesByRecent(articles)

	first := sorted[0].(map[string]interface{})
	if first["id"] != "2" {
		t.Errorf("expected article with valid date first, got id=%v", first["id"])
	}
}

// ---------------------------------------------------------------------------
// Unit tests: paginateArticles
// ---------------------------------------------------------------------------

func TestPaginateArticles_FirstPage(t *testing.T) {
	articles := make([]interface{}, 15)
	for i := range articles {
		articles[i] = map[string]interface{}{"id": i}
	}

	result := paginateArticles(articles, "1", "5")
	data := result["data"].([]interface{})
	if len(data) != 5 {
		t.Errorf("expected 5 items, got %d", len(data))
	}
	pagination := result["pagination"].(map[string]interface{})
	if pagination["total"].(int) != 15 {
		t.Errorf("expected total=15, got %v", pagination["total"])
	}
	if pagination["total_pages"].(int) != 3 {
		t.Errorf("expected total_pages=3, got %v", pagination["total_pages"])
	}
	if !pagination["has_next"].(bool) {
		t.Error("expected has_next=true")
	}
	if pagination["has_prev"].(bool) {
		t.Error("expected has_prev=false on page 1")
	}
}

func TestPaginateArticles_LastPage(t *testing.T) {
	articles := make([]interface{}, 7)
	for i := range articles {
		articles[i] = map[string]interface{}{"id": i}
	}

	result := paginateArticles(articles, "2", "5")
	data := result["data"].([]interface{})
	if len(data) != 2 {
		t.Errorf("expected 2 items on last page, got %d", len(data))
	}
	pagination := result["pagination"].(map[string]interface{})
	if pagination["has_next"].(bool) {
		t.Error("expected has_next=false on last page")
	}
	if !pagination["has_prev"].(bool) {
		t.Error("expected has_prev=true on last page")
	}
}

func TestPaginateArticles_EmptyInput(t *testing.T) {
	result := paginateArticles([]interface{}{}, "1", "10")
	data := result["data"].([]interface{})
	if len(data) != 0 {
		t.Errorf("expected 0 items for empty input, got %d", len(data))
	}
	pagination := result["pagination"].(map[string]interface{})
	if pagination["total"].(int) != 0 {
		t.Errorf("expected total=0, got %v", pagination["total"])
	}
	if pagination["total_pages"].(int) != 0 {
		t.Errorf("expected total_pages=0, got %v", pagination["total_pages"])
	}
}

func TestPaginateArticles_InvalidPageFallback(t *testing.T) {
	result := paginateArticles(make([]interface{}, 5), "bad", "10")
	pagination := result["pagination"].(map[string]interface{})
	if pagination["page"].(int) != 1 {
		t.Errorf("expected page=1 fallback, got %v", pagination["page"])
	}
}

func TestPaginateArticles_InvalidLimitFallback(t *testing.T) {
	result := paginateArticles(make([]interface{}, 5), "1", "bad")
	pagination := result["pagination"].(map[string]interface{})
	if pagination["limit"].(int) != 10 {
		t.Errorf("expected limit=10 fallback, got %v", pagination["limit"])
	}
}

// ---------------------------------------------------------------------------
// Unit tests: parsePublishDate
// ---------------------------------------------------------------------------

func TestParsePublishDate_ValidFormats(t *testing.T) {
	cases := []string{
		"2024-03-15",
		"2024-03-15 10:30:00",
		"2024-03-15T10:30:00Z",
	}
	for _, tc := range cases {
		t.Run(tc, func(t *testing.T) {
			_, ok := parsePublishDate(tc)
			if !ok {
				t.Errorf("expected parsePublishDate(%q) to succeed", tc)
			}
		})
	}
}

func TestParsePublishDate_InvalidFormat(t *testing.T) {
	_, ok := parsePublishDate("not-a-date")
	if ok {
		t.Error("expected parsePublishDate to fail for invalid input")
	}
}

func TestSortArticlesByID_NewestIDFirst(t *testing.T) {
	articles := []interface{}{
		map[string]interface{}{"id": "1771153", "publish_date": "2026-09-01"},
		map[string]interface{}{"id": float64(1780203)}, // JSON number
		map[string]interface{}{"id": "abc"},            // no numeric ID: last
		map[string]interface{}{"article_id": "1777938"},
		map[string]interface{}{"id": "1779239"},
	}
	sorted := sortArticlesByID(articles)

	got := make([]string, len(sorted))
	for i, item := range sorted {
		got[i] = firstNonEmptyField(item.(map[string]interface{}), "id", "article_id")
	}
	want := []string{"1780203", "1779239", "1777938", "1771153", "abc"}
	for i := range want {
		if got[i] != want[i] {
			t.Fatalf("sortArticlesByID order = %v, want %v", got, want)
		}
	}
	if first := articles[0].(map[string]interface{})["id"]; first != "1771153" {
		t.Error("sortArticlesByID must not mutate the input slice")
	}
}

func TestArticleListHandler_ArticlesCategory(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"data":{
			"withcat.com":[{"cat_id":"90","cat_name":"Articles"}],
			"nocat.com":[{"cat_id":"1","cat_name":"Business"},{"cat_id":"2","cat_name":"Lifestyle"}]
		}}`))
	}))
	defer srv.Close()
	orig := cmsService
	cmsService = cms.NewService(srv.URL, "test-key", 0)
	defer func() { cmsService = orig }()

	handler := articleListHandler(pageTemplatesFrom("../web/templates"))
	menu := func(url string) map[string]interface{} {
		return map[string]interface{}{"template": "magazine", "shared": map[string]interface{}{"navigation": map[string]interface{}{
			"staticItems": []interface{}{map[string]interface{}{"label": "Blog", "url": url}},
		}}}
	}
	for _, tt := range []struct {
		name string
		host string
		raw  map[string]interface{}
		want string // the page's categoryId prop, "" for the all-articles list
	}{
		{"menu links to the site's Articles category", "withcat.com", menu("/articles"), `"categoryId":"articles"`},
		{"menu links to /articles, no such category (localpages)", "nocat.com", menu("/articles"), ""},
		{"no menu link, Articles category", "withcat.com", menu("/blog"), ""},
	} {
		t.Run(tt.name, func(t *testing.T) {
			v := viper.New()
			v.Set("displayName", tt.host)
			config := &middlewares.ClientConfig{ViperConfig: v, Raw: tt.raw}
			req := httptest.NewRequest(http.MethodGet, "https://"+tt.host+"/articles", nil)
			req = req.WithContext(context.WithValue(req.Context(), middlewares.ClientConfigKey, config))
			rec := httptest.NewRecorder()
			handler.ServeHTTP(rec, req)
			html := rec.Body.String()
			if rec.Code != http.StatusOK {
				t.Fatalf("status = %d, want 200", rec.Code)
			}
			if tt.want != "" && !strings.Contains(html, tt.want) {
				t.Errorf("want the category page (%s)", tt.want)
			}
			if tt.want == "" && (strings.Contains(html, `"categoryId"`) || !strings.Contains(html, `"category":"articles"`)) {
				t.Error("want the all-articles list")
			}
		})
	}
}
