package matrix

import (
	"testing"

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

// extractThreadID is the pure logic extracted from the listener for testability.
// It mirrors the extraction in listener.go's EventMessage handler.
func extractThreadID(rawContent map[string]any) string {
	relatesTo, ok := rawContent["m.relates_to"].(map[string]any)
	if !ok {
		return ""
	}
	relType, _ := relatesTo["rel_type"].(string)
	if relType != "m.thread" {
		return ""
	}
	threadRoot, _ := relatesTo["event_id"].(string)
	return threadRoot
}

func TestExtractThreadID_ThreadMessage(t *testing.T) {
	raw := map[string]any{
		"body": "hello",
		"m.relates_to": map[string]any{
			"rel_type": "m.thread",
			"event_id": "$root123",
			"is_falling_back": true,
			"m.in_reply_to": map[string]any{
				"event_id": "$last456",
			},
		},
	}

	got := extractThreadID(raw)
	if got != "$root123" {
		t.Errorf("expected $root123, got %q", got)
	}
}

func TestExtractThreadID_ReplyNotThread(t *testing.T) {
	raw := map[string]any{
		"body": "hello",
		"m.relates_to": map[string]any{
			"m.in_reply_to": map[string]any{
				"event_id": "$evt789",
			},
		},
	}

	got := extractThreadID(raw)
	if got != "" {
		t.Errorf("expected empty string for non-thread reply, got %q", got)
	}
}

func TestExtractThreadID_NoRelatesTo(t *testing.T) {
	raw := map[string]any{
		"body": "plain message",
	}

	got := extractThreadID(raw)
	if got != "" {
		t.Errorf("expected empty string for plain message, got %q", got)
	}
}

func TestExtractThreadID_ReplaceRelation(t *testing.T) {
	raw := map[string]any{
		"body": "edited",
		"m.relates_to": map[string]any{
			"rel_type": "m.replace",
			"event_id": "$original",
		},
	}

	got := extractThreadID(raw)
	if got != "" {
		t.Errorf("expected empty string for m.replace, got %q", got)
	}
}

func TestExtractThreadID_ThreadWithoutEventID(t *testing.T) {
	raw := map[string]any{
		"m.relates_to": map[string]any{
			"rel_type": "m.thread",
			// missing event_id
		},
	}

	got := extractThreadID(raw)
	if got != "" {
		t.Errorf("expected empty string for thread without event_id, got %q", got)
	}
}

// extractThreadIDFromParsed is the typed-content fallback for E2EE events.
// Mirrors the fallback logic in listener.go.
func extractThreadIDFromParsed(parsed interface{}) string {
	if msgContent, ok := parsed.(*event.MessageEventContent); ok && msgContent.RelatesTo != nil {
		if threadParent := msgContent.RelatesTo.GetThreadParent(); threadParent != "" {
			return string(threadParent)
		}
	}
	return ""
}

func TestExtractThreadID_TypedFallback_Thread(t *testing.T) {
	parsed := &event.MessageEventContent{
		MsgType: event.MsgText,
		Body:    "hello from thread",
		RelatesTo: (&event.RelatesTo{}).SetThread(id.EventID("$root123"), id.EventID("$last456")),
	}

	got := extractThreadIDFromParsed(parsed)
	if got != "$root123" {
		t.Errorf("expected $root123 from typed fallback, got %q", got)
	}
}

func TestExtractThreadID_TypedFallback_NoRelatesTo(t *testing.T) {
	parsed := &event.MessageEventContent{
		MsgType: event.MsgText,
		Body:    "plain message",
	}

	got := extractThreadIDFromParsed(parsed)
	if got != "" {
		t.Errorf("expected empty string from typed fallback, got %q", got)
	}
}

func TestExtractThreadID_TypedFallback_ReplaceNotThread(t *testing.T) {
	parsed := &event.MessageEventContent{
		MsgType:   event.MsgText,
		Body:      "edited",
		RelatesTo: (&event.RelatesTo{}).SetReplace(id.EventID("$original")),
	}

	got := extractThreadIDFromParsed(parsed)
	if got != "" {
		t.Errorf("expected empty string for m.replace via typed fallback, got %q", got)
	}
}

func TestExtractThreadID_RawEmptyTypedWorks(t *testing.T) {
	// Simulates E2EE scenario: Raw map has no m.relates_to but Parsed does
	raw := map[string]any{
		"body":    "hello from thread",
		"msgtype": "m.text",
		// No m.relates_to in raw (can happen after E2EE decryption)
	}
	parsed := &event.MessageEventContent{
		MsgType: event.MsgText,
		Body:    "hello from thread",
		RelatesTo: (&event.RelatesTo{}).SetThread(id.EventID("$root123"), id.EventID("$last456")),
	}

	// Raw extraction should fail
	gotRaw := extractThreadID(raw)
	if gotRaw != "" {
		t.Errorf("expected empty from raw, got %q", gotRaw)
	}

	// Typed fallback should succeed
	gotTyped := extractThreadIDFromParsed(parsed)
	if gotTyped != "$root123" {
		t.Errorf("expected $root123 from typed fallback, got %q", gotTyped)
	}
}
