package matrix

import (
	"encoding/json"
	"testing"

	"maunium.net/go/mautrix/event"
	"maunium.net/go/mautrix/id"
)

// TestThreadRelatesToStructure verifies the JSON structure produced by SetThread
// matches the Matrix spec for m.thread events.
func TestThreadRelatesToStructure(t *testing.T) {
	rel := (&event.RelatesTo{}).SetThread(id.EventID("$root"), id.EventID("$last"))

	data, err := json.Marshal(rel)
	if err != nil {
		t.Fatalf("marshal error: %v", err)
	}

	var m map[string]any
	if err := json.Unmarshal(data, &m); err != nil {
		t.Fatalf("unmarshal error: %v", err)
	}

	if m["rel_type"] != "m.thread" {
		t.Errorf("expected rel_type=m.thread, got %v", m["rel_type"])
	}
	if m["event_id"] != "$root" {
		t.Errorf("expected event_id=$root, got %v", m["event_id"])
	}
	if m["is_falling_back"] != true {
		t.Errorf("expected is_falling_back=true, got %v", m["is_falling_back"])
	}

	inReplyTo, ok := m["m.in_reply_to"].(map[string]any)
	if !ok {
		t.Fatal("expected m.in_reply_to to be an object")
	}
	if inReplyTo["event_id"] != "$last" {
		t.Errorf("expected m.in_reply_to.event_id=$last, got %v", inReplyTo["event_id"])
	}
}

// TestThreadRelatesToStructure_SameRootAndFallback verifies that when root == fallback,
// the structure is still correct.
func TestThreadRelatesToStructure_SameRootAndFallback(t *testing.T) {
	rel := (&event.RelatesTo{}).SetThread(id.EventID("$root"), id.EventID("$root"))

	data, err := json.Marshal(rel)
	if err != nil {
		t.Fatalf("marshal error: %v", err)
	}

	var m map[string]any
	if err := json.Unmarshal(data, &m); err != nil {
		t.Fatalf("unmarshal error: %v", err)
	}

	if m["rel_type"] != "m.thread" {
		t.Errorf("expected rel_type=m.thread, got %v", m["rel_type"])
	}
	if m["event_id"] != "$root" {
		t.Errorf("expected event_id=$root, got %v", m["event_id"])
	}
}
