package dto

import (
	"encoding/json"
	"testing"
	"time"

	"github.com/smartystreets/goconvey/convey"
	"github.com/tidbcloud/tiinf/sdk/auditlog"
)

func TestConvertToDBEvent(t *testing.T) {
	detailsM := map[string]string{
		"password":     "qwerty",
		"phone_number": "+86 13111111111",
		"name":         "john",
	}

	convey.Convey("TestConvertToDBEvent", t, func() {
		detailsB, err := json.Marshal(&detailsM)
		convey.So(err, convey.ShouldBeNil)

		details := string(detailsB)

		convey.Convey("invalid ip", func() {
			now := time.Now()
			e := &auditlog.Event{
				Type:                auditlog.EventChangePassword,
				EndsAt:              now,
				OperatorIP:          "a.b.c.d",
				OrgID:               2,
				ProjectID:           3,
				ClusterID:           0,
				TraceID:             "trace_id",
				Result:              auditlog.ResultFailed,
				Details:             "",
				OperatorType:        auditlog.OperatorTypeUser,
				OperatorID:          1,
				OperatorEmail:       "",
				OperatorLoginMethod: "google",
				OrgName:             "",
				ProjectName:         "",
				ClusterName:         "",
			}

			dbEvent := ConvertToDBEvent(e)
			convey.So(dbEvent.Type, convey.ShouldEqual, auditlog.EventChangePassword)
			convey.So(dbEvent.EndsAt, convey.ShouldEqual, now)
			convey.So(dbEvent.OperatorType, convey.ShouldEqual, auditlog.OperatorTypeUser)
			convey.So(dbEvent.OperatorID, convey.ShouldEqual, 1)
			convey.So(dbEvent.OperatorIP, convey.ShouldEqual, "a.b.c.d")
			convey.So(dbEvent.OperatorLoginMethod, convey.ShouldEqual, "google")
			convey.So(dbEvent.OrgID, convey.ShouldEqual, 2)
			convey.So(dbEvent.ProjectID, convey.ShouldEqual, 3)
			convey.So(dbEvent.ClusterID, convey.ShouldEqual, 0)
			convey.So(dbEvent.TraceID, convey.ShouldEqual, "trace_id")
			convey.So(dbEvent.Result, convey.ShouldEqual, auditlog.ResultFailed)
			convey.So(dbEvent.Details, convey.ShouldEqual, "")
		})

		convey.Convey("masking", func() {
			now := time.Now()
			e := &auditlog.Event{
				Type:                auditlog.EventImportDataFromGCP,
				EndsAt:              now,
				OperatorIP:          "a.b.c.d",
				OrgID:               2,
				ProjectID:           3,
				ClusterID:           0,
				TraceID:             "trace_id",
				Result:              auditlog.ResultFailed,
				Details:             details,
				OperatorEmail:       "",
				OperatorLoginMethod: "google",
				OrgName:             "",
				ProjectName:         "",
				ClusterName:         "",
			}
			dbEvent := ConvertToDBEvent(e)

			m := map[string]string{}
			err := json.Unmarshal([]byte(dbEvent.Details), &m)
			convey.So(err, convey.ShouldBeNil)

			convey.So(m["name"], convey.ShouldEqual, "john")
			convey.So(m["phone_number"], convey.ShouldEqual, "+?? ???????????")
		})
	})
}
