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"
	"git.noahlan.cn/noahlan/ntool-biz/core/orm/nent/mixins"
	"git.noahlan.cn/noahlan/ntool/nrandom"
)

type LoginRecord struct {
	ent.Schema
}

func (LoginRecord) Fields() []ent.Field {
	return []ent.Field{
		field.Int64("user_id").Comment("User ID | 用户ID"),
		field.Time("last_login_at").Optional().SchemaType(map[string]string{dialect.MySQL: "datetime"}).
			Comment("LastLogin Time | 最近一次登录时间"),
		field.String("last_login_ipv4").Optional().Comment("LastLogin IPv4 | 最近一次登录IPv4"),
		field.String("last_login_device").Optional().Comment("LastLogin Device | 最近一次登录设备"),
		field.String("last_login_UA").Optional().
			SchemaType(map[string]string{dialect.MySQL: "varchar(1024)"}).
			Comment("LastLogin UA | 最近一次登录浏览器UA"),
		field.Uint64("login_count").Default(1).Comment("Login Count | 总登录次数"),
	}
}

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

func (LoginRecord) Edges() []ent.Edge {
	return []ent.Edge{
		edge.From("user", User.Type).
			Ref("loginRecord").
			Field("user_id").
			Unique().
			Required(),
	}
}

func (LoginRecord) Indexes() []ent.Index {
	return []ent.Index{}
}

func (LoginRecord) Annotations() []schema.Annotation {
	return []schema.Annotation{
		entsql.WithComments(true),
		entsql.Annotation{Table: "sys_login_record"},
		schema.Comment("系统用户登录记录表"),
	}
}
