package handlers

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

	"github.com/gin-gonic/gin"
)

func TestScanJSON_ValidObject(t *testing.T) {
	var dest json.RawMessage
	s := scanJSON(&dest)
	if err := s.Scan([]byte(`{"key":"value"}`)); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if string(dest) != `{"key":"value"}` {
		t.Fatalf("expected {\"key\":\"value\"}, got %s", dest)
	}
}

func TestScanJSON_ValidArray(t *testing.T) {
	var dest json.RawMessage
	s := scanJSON(&dest)
	if err := s.Scan([]byte(`[1,2,3]`)); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if string(dest) != `[1,2,3]` {
		t.Fatalf("expected [1,2,3], got %s", dest)
	}
}

func TestScanJSON_EmptyString(t *testing.T) {
	var dest json.RawMessage
	s := scanJSON(&dest)
	if err := s.Scan(""); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if string(dest) != "{}" {
		t.Fatalf("expected {}, got %s", dest)
	}
}

func TestScanJSON_Nil(t *testing.T) {
	var dest json.RawMessage
	s := scanJSON(&dest)
	if err := s.Scan(nil); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if string(dest) != "{}" {
		t.Fatalf("expected {}, got %s", dest)
	}
}

func TestScanJSON_BinaryGarbage(t *testing.T) {
	var dest json.RawMessage
	s := scanJSON(&dest)
	// The exact scenario from the bug: STX control character
	if err := s.Scan([]byte{0x02, 0x03, 0x04}); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if string(dest) != "{}" {
		t.Fatalf("expected {} for binary garbage, got %s", dest)
	}
}

func TestScanJSON_TruncatedJSON(t *testing.T) {
	var dest json.RawMessage
	s := scanJSON(&dest)
	if err := s.Scan([]byte(`{"key":"val`)); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if string(dest) != "{}" {
		t.Fatalf("expected {} for truncated JSON, got %s", dest)
	}
}

func TestScanJSON_StringDialect(t *testing.T) {
	// SQLite returns strings, not []byte
	var dest json.RawMessage
	s := scanJSON(&dest)
	if err := s.Scan(`{"sqlite":"mode"}`); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if string(dest) != `{"sqlite":"mode"}` {
		t.Fatalf("expected {\"sqlite\":\"mode\"}, got %s", dest)
	}
}

func TestScanJSON_StringDialect_Corrupt(t *testing.T) {
	var dest json.RawMessage
	s := scanJSON(&dest)
	if err := s.Scan("\x02\x03garbage"); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if string(dest) != "{}" {
		t.Fatalf("expected {} for corrupt string, got %s", dest)
	}
}

func TestSafeJSON_ValidPayload(t *testing.T) {
	gin.SetMode(gin.TestMode)
	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)

	SafeJSON(c, http.StatusOK, gin.H{"status": "ok"})

	if w.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", w.Code)
	}
	if ct := w.Header().Get("Content-Type"); ct != "application/json; charset=utf-8" {
		t.Fatalf("expected JSON content-type, got %s", ct)
	}

	var result map[string]string
	if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
		t.Fatalf("response is not valid JSON: %v", err)
	}
	if result["status"] != "ok" {
		t.Fatalf("expected status=ok, got %s", result["status"])
	}
}

func TestSafeJSON_CorruptRawMessage(t *testing.T) {
	gin.SetMode(gin.TestMode)
	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)

	// Simulate the exact bug: a struct with a corrupt json.RawMessage
	type response struct {
		ID       string          `json:"id"`
		Settings json.RawMessage `json:"settings"`
	}
	resp := response{
		ID:       "test-123",
		Settings: json.RawMessage{0x02, 0x03}, // binary garbage
	}

	SafeJSON(c, http.StatusOK, resp)

	// Should get 500, not a truncated 200
	if w.Code != http.StatusInternalServerError {
		t.Fatalf("expected 500 for corrupt RawMessage, got %d", w.Code)
	}

	// Body should be valid JSON with error message
	var result map[string]string
	if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
		t.Fatalf("error response is not valid JSON: %v", err)
	}
	if result["error"] != "response serialization failed" {
		t.Fatalf("unexpected error message: %s", result["error"])
	}
}

func TestSafeJSON_PaginatedWithCorrupt(t *testing.T) {
	gin.SetMode(gin.TestMode)
	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)

	// If scanJSON is hardened, this should never happen — but SafeJSON
	// is the second line of defense if something slips through.
	type item struct {
		Settings json.RawMessage `json:"settings"`
	}
	type paginated struct {
		Data  []item `json:"data"`
		Total int    `json:"total"`
	}

	resp := paginated{
		Data: []item{
			{Settings: json.RawMessage(`{"ok":true}`)},
			{Settings: json.RawMessage{0xFF, 0xFE}}, // corrupt
		},
		Total: 2,
	}

	SafeJSON(c, http.StatusOK, resp)

	if w.Code != http.StatusInternalServerError {
		t.Fatalf("expected 500 for paginated response with corrupt item, got %d", w.Code)
	}
}

// ── Driver buffer aliasing tests ────────────
// These verify the fix for the v0.21.7 corruption bug: scanJSON must
// copy []byte from the database driver, not alias it. Without the copy,
// rows.Next() can overwrite the buffer and corrupt previously-scanned
// json.RawMessage values in a paginated list.

func TestScanJSON_ByteSliceNotAliased(t *testing.T) {
	var dest json.RawMessage
	s := scanJSON(&dest)

	// Simulate driver buffer with valid JSON
	buf := []byte(`{"key":"value"}`)
	if err := s.Scan(buf); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	// Simulate driver reusing the buffer on next rows.Scan()
	copy(buf, []byte(`invalid_json!!`))

	// dest must still hold the original valid value
	if !json.Valid(dest) {
		t.Fatalf("dest corrupted after source buffer reuse: %q", dest)
	}
	if string(dest) != `{"key":"value"}` {
		t.Fatalf("expected original value, got %q", dest)
	}
}

func TestScanJSON_ByteSliceIsolation_MultiRow(t *testing.T) {
	// Simulate scanning two rows through the same driver buffer,
	// as happens in ListChannels when lib/pq reuses memory.
	var dest1, dest2 json.RawMessage

	// Row 1
	buf := make([]byte, 64)
	row1 := []byte(`{"row":1,"selector":"abc"}`)
	copy(buf, row1)
	s1 := scanJSON(&dest1)
	if err := s1.Scan(buf[:len(row1)]); err != nil {
		t.Fatalf("row 1 scan error: %v", err)
	}

	// Row 2 — driver reuses same buffer
	row2 := []byte(`{"row":2}`)
	copy(buf, row2)
	s2 := scanJSON(&dest2)
	if err := s2.Scan(buf[:len(row2)]); err != nil {
		t.Fatalf("row 2 scan error: %v", err)
	}

	// Both must retain their original values
	if string(dest1) != `{"row":1,"selector":"abc"}` {
		t.Fatalf("dest1 corrupted by row 2 scan: %q", dest1)
	}
	if string(dest2) != `{"row":2}` {
		t.Fatalf("dest2 unexpected value: %q", dest2)
	}

	// Both must be independently valid JSON
	if !json.Valid(dest1) {
		t.Fatalf("dest1 not valid JSON after multi-row scan: %q", dest1)
	}
	if !json.Valid(dest2) {
		t.Fatalf("dest2 not valid JSON after multi-row scan: %q", dest2)
	}
}
