package mloco

import (
	"reflect"
	"testing"
	"time"
)

func TestBSONRoundTrip(t *testing.T) {
	doc := map[string]any{"userId": int64(123456789),
		"name":    "test",
		"age":     int32(42),
		"active":  true,
		"score":   float64(3.14),
		"nothing": nil,
		"nested":  docMap{"x": int32(1)},
		"arr":     arrList{int32(1), "two", true},
		"when":    time.Date(2026, 9, 2, 12, 0, 0, 0, time.UTC),
		"bin":     binaryData{subtype: 0x00, data: []byte{1, 2, 3}},
	}
	enc := encodeBSONDocument(map[string]any{"d": docMap(doc)})
	root, err := decodeBSONDocument(enc)
	if err != nil {
		t.Fatalf("decode failed: %v", err)
	}
	got := root["d"].(map[string]any)
	if got["userId"] != int64(123456789) {
		t.Errorf("userId = %v", got["userId"])
	}
	if got["name"] != "test" {
		t.Errorf("name = %v", got["name"])
	}
	if got["active"] != true {
		t.Errorf("active = %v", got["active"])
	}
	if got["score"] != 3.14 {
		t.Errorf("score = %v", got["score"])
	}
	if got["nothing"] != nil {
		t.Errorf("nothing = %v", got["nothing"])
	}
	nested, ok := got["nested"].(map[string]any)
	if !ok || nested["x"] != int32(1) {
		t.Errorf("nested = %v", got["nested"])
	}
	arr, ok := got["arr"].([]any)
	if !ok || !reflect.DeepEqual(arr, []any{int32(1), "two", true}) {
		t.Errorf("arr = %v", got["arr"])
	}
	if got["when"] != time.Date(2026, 9, 2, 12, 0, 0, 0, time.UTC) {
		t.Errorf("when = %v", got["when"])
	}
	if bin, ok := got["bin"].(binaryData); !ok || bin.subtype != 0x00 || !reflect.DeepEqual(bin.data, []byte{1, 2, 3}) {
		t.Errorf("bin = %v", got["bin"])
	}
}

func TestBSONDecodeRaw(t *testing.T) {
	raw := []byte{
		0x0f, 0x00, 0x00, 0x00,
		0x02, 'a', 0x00, 0x03, 0x00, 0x00, 0x00, 'h', 'i', 0x00,
		0x00,
	}
	doc, err := decodeBSONDocument(raw)
	if err != nil {
		t.Fatalf("decode failed: %v", err)
	}
	if doc["a"] != "hi" {
		t.Errorf("a = %v", doc["a"])
	}
}
