package routes

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

	"bitbucket.org/imediabrands/oos-service/internal/cms"
	"github.com/julienschmidt/httprouter"
)

// -----------------------------------------------------------------------------
// normalizeImagesAttr / normalizeImagesAttrList
// -----------------------------------------------------------------------------

func TestNormalizeImagesAttr_ValidJSONString(t *testing.T) {
	article := map[string]interface{}{
		"id":          "1",
		"images_attr": `{"img":{"alt":"sweet vs dry wine"}}`,
	}

	normalizeImagesAttr(article)

	parsed, ok := article["images_attr"].(map[string]interface{})
	if !ok {
		t.Fatalf("expected images_attr to become a map, got %T: %v", article["images_attr"], article["images_attr"])
	}
	img, ok := parsed["img"].(map[string]interface{})
	if !ok {
		t.Fatalf("expected images_attr.img to be a map, got %T", parsed["img"])
	}
	if img["alt"] != "sweet vs dry wine" {
		t.Fatalf("expected alt %q, got %q", "sweet vs dry wine", img["alt"])
	}
}

func TestNormalizeImagesAttr_EmptyOrMissingLeftUntouched(t *testing.T) {
	cases := []map[string]interface{}{
		{"id": "1", "images_attr": ""},
		{"id": "2"},
		{"id": "3", "images_attr": nil},
	}
	for _, article := range cases {
		before := article["images_attr"]
		normalizeImagesAttr(article)
		if article["images_attr"] != before {
			t.Fatalf("expected images_attr to be left untouched, got %v", article["images_attr"])
		}
	}
}

func TestNormalizeImagesAttr_InvalidJSONLeftUntouched(t *testing.T) {
	article := map[string]interface{}{"id": "1", "images_attr": "not json"}
	normalizeImagesAttr(article)
	if article["images_attr"] != "not json" {
		t.Fatalf("expected invalid JSON to be left untouched, got %v", article["images_attr"])
	}
}

func TestNormalizeImagesAttrList(t *testing.T) {
	items := []interface{}{
		map[string]interface{}{"id": "1", "images_attr": `{"img":{"alt":"a"}}`},
		map[string]interface{}{"id": "2", "images_attr": `{"img":{"alt":"b"}}`},
		"not-an-article", // must be skipped without panicking
	}

	normalizeImagesAttrList(items)

	for _, item := range items[:2] {
		article := item.(map[string]interface{})
		if _, ok := article["images_attr"].(map[string]interface{}); !ok {
			t.Fatalf("expected images_attr to be normalized for article %v", article["id"])
		}
	}
}

// -----------------------------------------------------------------------------
// DataArticleHandler: images_attr normalization end-to-end
// -----------------------------------------------------------------------------

func TestDataArticleHandler_NormalizesImagesAttr(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{
			"data": {
				"id": "1775223",
				"title": "Sweet vs Dry Wine",
				"images_attr": "{\"img\":{\"alt\":\"sweet vs dry wine\"}}"
			}
		}`))
	}))
	defer server.Close()

	origCmsService := cmsService
	cmsService = cms.NewService(server.URL, "test-key", 0)
	defer func() { cmsService = origCmsService }()

	req := httptest.NewRequest("GET", "/data/article/1775223", nil)
	params := httprouter.Params{httprouter.Param{Key: "id", Value: "1775223"}}
	req = req.WithContext(context.WithValue(req.Context(), httprouter.ParamsKey, params))
	rr := httptest.NewRecorder()

	DataArticleHandler().ServeHTTP(rr, req)

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
	}

	var parsed struct {
		Data struct {
			ImagesAttr struct {
				Img struct {
					Alt string `json:"alt"`
				} `json:"img"`
			} `json:"images_attr"`
		} `json:"data"`
	}
	if err := json.Unmarshal(rr.Body.Bytes(), &parsed); err != nil {
		t.Fatalf("expected images_attr to decode as a nested object, got body %s: %v", rr.Body.String(), err)
	}
	if parsed.Data.ImagesAttr.Img.Alt != "sweet vs dry wine" {
		t.Fatalf("expected alt %q, got %q", "sweet vs dry wine", parsed.Data.ImagesAttr.Img.Alt)
	}
}

// An ID that isn't a number gets the CMS's missing-article answer, without a CMS request.
func TestDataArticleHandler_NonNumericID(t *testing.T) {
	cmsCalls := 0
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		cmsCalls++
		w.Write([]byte(`{"data":[],"error":"Please pass article id"}`))
	}))
	defer server.Close()

	origCmsService := cmsService
	cmsService = cms.NewService(server.URL, "test-key", 0)
	defer func() { cmsService = origCmsService }()

	req := httptest.NewRequest("GET", "/data/article/1760806x", nil)
	params := httprouter.Params{httprouter.Param{Key: "id", Value: "1760806x"}}
	req = req.WithContext(context.WithValue(req.Context(), httprouter.ParamsKey, params))
	rr := httptest.NewRecorder()

	DataArticleHandler().ServeHTTP(rr, req)

	if rr.Code != http.StatusOK || rr.Body.String() != `{"data":false}` {
		t.Fatalf("got %d %s, want 200 {\"data\":false}", rr.Code, rr.Body.String())
	}
	if cmsCalls != 0 {
		t.Fatalf("CMS was called %d times, want 0", cmsCalls)
	}
}

// -----------------------------------------------------------------------------
// DataArticleHandler: own-site links in content point at their final URLs
// -----------------------------------------------------------------------------

func TestDataArticleHandler_RewritesInternalLinks(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		switch r.URL.Query().Get("id") {
		case "1780517":
			w.Write([]byte(`{"data": {
				"id": "1780517",
				"category": "Weight Loss Tips",
				"slug_title": "calorie-deficit-guide-for-safer-healthier-weight-loss",
				"content": "<p><a href=\"https://www.centerweightloss.com/weight-loss/1760498-easy-homemade-weight-loss-drinks-for-a-healthier-you/\">drinks</a> <a href=\"https://www.youtube.com/watch?v=1\">video</a></p>"
			}}`))
		case "1760498":
			w.Write([]byte(`{"data": {
				"id": "1760498",
				"category": "Weight Loss Tips",
				"slug_title": "easy-homemade-weight-loss-drinks-for-a-healthier-you"
			}}`))
		default:
			w.Write([]byte(`{"data": null}`))
		}
	}))
	defer server.Close()

	origCmsService := cmsService
	cmsService = cms.NewService(server.URL, "test-key", time.Minute)
	defer func() { cmsService = origCmsService }()

	req := httptest.NewRequest("GET", "/data/article/1780517", nil)
	req.Header.Set("X-Forwarded-Host", "www.centerweightloss.com")
	params := httprouter.Params{httprouter.Param{Key: "id", Value: "1780517"}}
	req = req.WithContext(context.WithValue(req.Context(), httprouter.ParamsKey, params))
	rr := httptest.NewRecorder()

	DataArticleHandler().ServeHTTP(rr, req)

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
	}
	var parsed struct {
		Data struct {
			Content string `json:"content"`
		} `json:"data"`
	}
	if err := json.Unmarshal(rr.Body.Bytes(), &parsed); err != nil {
		t.Fatalf("decode body %s: %v", rr.Body.String(), err)
	}
	want := `<p><a href="/weight-loss-tips/1760498-easy-homemade-weight-loss-drinks-for-a-healthier-you">drinks</a> <a href="https://www.youtube.com/watch?v=1">video</a></p>`
	if parsed.Data.Content != want {
		t.Fatalf("content = %s\nwant      %s", parsed.Data.Content, want)
	}
}
