package model

import (
	"encoding/json"
	"fmt"
	"reflect"
	"testing"

	"github.com/stretchr/testify/require"
)

type marshalTest struct {
	ent interface{}
	exp string
}

func runMarshalUnmarshalTests(t *testing.T, tests ...marshalTest) {
	for i, tt := range tests {
		t.Run(fmt.Sprintf("%s#%d", t.Name(), i), func(t *testing.T) {
			// marshal
			act, err := json.MarshalIndent(tt.ent, "", "  ")
			require.NoError(t, err, fmt.Sprintf("marsharl %+v", tt.ent))
			require.Equal(t, tt.exp, string(act))

			// unmarshal
			val := reflect.New(reflect.TypeOf(tt.ent))
			err = json.Unmarshal(act, val.Interface())
			require.NoError(t, err, fmt.Sprintf("unmarshal %s", string(act)))
			require.Equal(t, tt.ent, val.Elem().Interface())
		})
	}
}

func TestMarshalUnmarshalUser(t *testing.T) {
	runMarshalUnmarshalTests(t, marshalTest{
		User{
			ID:    3,
			Email: "qa@pingcap.com",
		},
		`{
  "id": 3,
  "email": "qa@pingcap.com"
}`,
	})
}
