package threadsapi

import (
	"encoding/json"
	"testing"
)

func TestParseMediaRefIDObjectAndString(t *testing.T) {
	obj := json.RawMessage(`{"id":"123"}`)
	if got := parseMediaRefID(obj); got != "123" {
		t.Fatalf("object ref: got %q", got)
	}
	str := json.RawMessage(`"456"`)
	if got := parseMediaRefID(str); got != "456" {
		t.Fatalf("string ref: got %q", got)
	}
}

func TestNormalizeReplyItemPrefersRepliedTo(t *testing.T) {
	item := normalizeReplyItem(replyItemRaw{
		ID:        "child",
		ParentID:  "legacy-parent",
		RepliedTo: json.RawMessage(`{"id":"real-parent"}`),
		Text:      "hello",
	})
	if item.RepliedToID != "real-parent" {
		t.Fatalf("expected replied_to id, got %q", item.RepliedToID)
	}
}

func TestNormalizeReplyItemKeepsMediaURLs(t *testing.T) {
	item := normalizeReplyItem(replyItemRaw{
		ID:           "img-reply",
		MediaType:    "IMAGE",
		MediaURL:     "https://example.com/photo.jpg",
		ThumbnailURL: "https://example.com/thumb.jpg",
		GifURL:       "https://example.com/cat.gif",
	})
	if item.MediaURL != "https://example.com/photo.jpg" {
		t.Fatalf("media_url: got %q", item.MediaURL)
	}
	if item.GifURL != "https://example.com/cat.gif" {
		t.Fatalf("gif_url: got %q", item.GifURL)
	}
}

func TestNormalizeReplyItemParsesCarouselChildren(t *testing.T) {
	item := normalizeReplyItem(replyItemRaw{
		ID:        "carousel-reply",
		MediaType: "CAROUSEL_ALBUM",
		Children:  json.RawMessage(`{"data":[{"id":"c1","media_type":"IMAGE","media_url":"https://example.com/1.jpg"},{"id":"c2","media_type":"VIDEO","media_url":"https://example.com/2.mp4","thumbnail_url":"https://example.com/2.jpg"}]}`),
	})
	if len(item.MediaChildren) != 2 {
		t.Fatalf("expected 2 media children, got %d", len(item.MediaChildren))
	}
	if item.MediaChildren[0].MediaURL != "https://example.com/1.jpg" {
		t.Fatalf("first child media_url: got %q", item.MediaChildren[0].MediaURL)
	}
	if item.MediaChildren[1].ThumbnailURL != "https://example.com/2.jpg" {
		t.Fatalf("second child thumbnail_url: got %q", item.MediaChildren[1].ThumbnailURL)
	}
}

func TestParseMediaChildrenAcceptsArray(t *testing.T) {
	children := parseMediaChildren(json.RawMessage(`[{"id":"x","media_type":"IMAGE","media_url":"https://example.com/x.jpg"}]`))
	if len(children) != 1 || children[0].ID != "x" {
		t.Fatalf("unexpected children: %#v", children)
	}
}
