package entity

import (
	"fmt"
	"testing"

	"go.mongodb.org/mongo-driver/bson"
)

func TestOne(t *testing.T) {
	one := One{
		ID:   "myname",
		Type: "mytype",
	}
	q := one.Query()
	if want := fmt.Sprint(bson.M{ID: one.ID}); want != fmt.Sprint(q) {
		t.Error(want, q)
	}
}

func TestOneMarshalBSON(t *testing.T) {
	cases := map[string]struct {
		sameAsQuery bool
		one         interface{}
	}{
		"query no modified change": {
			sameAsQuery: true,
			one:         (One{Name: "hello", Type: "world", Modified: 1}).Query(),
		},
		"modified changes": {
			one: One{Name: "hello", Type: "world", Modified: 1},
		},
		"w/ connections": {
			one: One{Name: "hello", Type: "world", Modified: 1, Connections: map[string]Connection{"hi": Connection{Relationship: "mom"}}},
		},
		"w/ attachments": {
			one: One{Name: "hello", Type: "world", Modified: 1, Attachments: map[string]Attachment{"hello": Attachment{"/world"}}},
		},
	}

	for name, d := range cases {
		c := d
		t.Run(name, func(t *testing.T) {
			b, err := bson.Marshal(c.one)
			if err != nil {
				t.Fatal(err)
			}
			one := One{}
			if err := bson.Unmarshal(b, &one); err != nil {
				t.Fatal(err)
			}
			if !c.sameAsQuery {
				if one.Modified < 2 {
					t.Error(one.Modified)
				}
			}
		})
	}
}
