package mo

import (
	"context"
	"reflect"
	"testing"
)

const (
	moTestSimpleDb   = "test"
	moTestSimpleColl = moTestSimpleDb
)

func newSimple() *Shortcut {
	client, err := NewClient("mongodb://root:abcd1234@192.168.0.224:27017/?authSource=admin&readPreference=primary&appname=golandTest&directConnection=true&ssl=false")
	if err != nil {
		panic(err)
	}
	coll := client.Database(moTestSimpleDb).Collection(moTestSimpleColl)
	return NewShortcut(coll)
}

func TestSimple_InsertOne(t *testing.T) {
	sim := newSimple()
	testData := M{
		"name":    "xiaoming",
		"age":     10,
		"hobby":   "learning to mongodb",
		"enabled": true,
	}
	ret, err := sim.InsertOne(testData)
	if err != nil {
		t.Error(err)
		return
	}
	t.Log(ret.InsertedID, reflect.TypeOf(ret.InsertedID).Kind())
}

func TestSimple_InsertMany(t *testing.T) {
	sim := newSimple()
	testData := []any{
		M{
			"name":    "lihua",
			"age":     11,
			"hobby":   "music",
			"enabled": true,
		},
		M{
			"name":    "amy",
			"age":     12,
			"hobby":   "sport",
			"enabled": false,
		},
	}
	ret, err := sim.InsertMany(testData)
	if err != nil {
		t.Error(err)
		return
	}
	t.Log(ret.InsertedIDs, reflect.TypeOf(ret.InsertedIDs).Kind())
}

func TestSimple_Indexes(t *testing.T) {
	sim := newSimple()
	idxRet, err := sim.Indexes().CreateOne(context.Background(), NewIndex("idxa"))
	if err != nil {
		t.Error("CreateOne:", err)
		return
	}
	t.Log(idxRet)

	cursor, err := sim.Indexes().List(context.Background())
	if err != nil {
		t.Error(err)
		return
	}

	idxList, err := ResolveIndexName(cursor)
	if err != nil {
		t.Error(err)
		return
	}
	t.Log(idxList)

	raw, err := sim.Indexes().DropOne(context.Background(), IndexName("idxa"))
	if err != nil {
		t.Error(err)
		return
	}

	t.Log(raw.String())
}
