package schema

import (
	"entgo.io/ent"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/entsql"
	"entgo.io/ent/schema"
	"entgo.io/ent/schema/edge"
	"entgo.io/ent/schema/field"
	"entgo.io/ent/schema/index"
	"git.noahlan.cn/noahlan/ntool-biz/core/orm/nent/mixins"
	"git.noahlan.cn/noahlan/ntool/nrandom"
)

type UserMeta struct {
	ent.Schema
}

func (UserMeta) Fields() []ent.Field {
	return []ent.Field{
		field.Int64("user_id").
			Comment("User id | 用户ID"),
		field.String("key").
			Optional(). // default null
			SchemaType(map[string]string{dialect.MySQL: "varchar(255)"}).
			Comment("Key | 键"),
		field.Text("value").
			Optional(). // default null
			Comment("Key | 值"),
	}
}

func (UserMeta) Mixin() []ent.Mixin {
	return []ent.Mixin{
		mixins.NewDistributedIDMixin(func() int64 { return nrandom.SnowflakeId() }),
		mixins.TimeMixin{},
		mixins.OptimisticLockMixin{},
	}
}

func (UserMeta) Edges() []ent.Edge {
	return []ent.Edge{
		edge.From("user", User.Type).
			Ref("metas").
			Field("user_id").
			Required().
			Unique(), // many to one
	}
}

func (UserMeta) Indexes() []ent.Index {
	return []ent.Index{
		index.Fields("key"),
		index.Fields("user_id"),
		index.Fields("user_id", "key").Unique(),
	}
}

func (UserMeta) Annotations() []schema.Annotation {
	return []schema.Annotation{
		entsql.WithComments(true),
		entsql.Annotation{Table: "sys_usermeta"},
		schema.Comment("系统用户元数据表"),
	}
}
