package mloco

import (
	"encoding/hex"
	"testing"
)

func TestParseChatIDField(t *testing.T) {
	cases := []struct {
		in   any
		want int64
	}{
		{int64(42), 42},
		{int64(123456), 123456},
		{int32(7), 7},
		{float64(9), 9},
		{"123", 123},
		{"abc", 0},
	}
	for _, c := range cases {
		if got := parseChatIDField(c.in); got != c.want {
			t.Errorf("parseChatIDField(%v) = %d, want %d", c.in, got, c.want)
		}
	}
}

func TestChatLogFromMap(t *testing.T) {
	m := map[string]any{
		"logId":    int64(100),
		"chatId":   int64(200),
		"authorId": int64(300),
		"message":  "hello",
		"type":     int32(1),
		"sendAt":   int64(1700000000000),
	}
	log := chatLogFromMap(m)
	if log.LogID != 100 || log.ChatID != 200 || log.AuthorID != 300 || log.Message != "hello" || log.Type != 1 || log.SendAt != 1700000000000 {
		t.Errorf("chatLogFromMap = %+v", log)
	}
}

func TestIsPushMethod(t *testing.T) {
	if !isPushMethod("MSG") {
		t.Error("MSG should be a push method")
	}
	if !isPushMethod("CHANGESVR") {
		t.Error("CHANGESVR should be a push method")
	}
	if isPushMethod("WRITE") {
		t.Error("WRITE should not be a push method")
	}
}

func TestBSONWithArrList(t *testing.T) {
	doc := encodeBSONDocument(docMap{
		"chatIds": arrList{"1", "2"},
		"chatId":  int64(5),
	})
	parsed, err := decodeBSONDocument(doc)
	if err != nil {
		t.Fatalf("decode: %v", err)
	}
	arr, ok := parsed["chatIds"].([]any)
	if !ok || len(arr) != 2 || arr[0] != "1" {
		t.Errorf("chatIds = %#v", parsed["chatIds"])
	}
	if parsed["chatId"] != int64(5) {
		t.Errorf("chatId = %#v", parsed["chatId"])
	}
}

func TestHexToPacketPush(t *testing.T) {
	body := encodeBSONDocument(docMap{
		"chatLog": docMap{
			"logId":    int64(1),
			"chatId":   int64(2),
			"authorId": int64(3),
			"message":  "x",
			"type":     int32(1),
		},
	})
	pkt := packet{
		header: packetHeader{
			ID:       0,
			Method:   "MSG",
			bodyType: 1,
			bodyLen:  uint32(len(body)),
		},
		body: body,
	}
	dump, err := HexToPacket(hex.EncodeToString(pkt.encode()))
	if err != nil {
		t.Fatalf("HexToPacket: %v", err)
	}
	if dump.Method != "MSG" {
		t.Errorf("method = %q", dump.Method)
	}
}
