package schema

import (
	"entgo.io/ent"
	"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 User struct {
	ent.Schema
}

func (User) Fields() []ent.Field {
	return []ent.Field{
		field.String("username").Unique().Comment("User's login name | 登录名"),
		field.String("phone_number").Nillable().Optional().Unique().Comment("Phone number | 手机号"),
		field.String("email").Nillable().Optional().Unique().Comment("Email | 邮箱号"),
		field.String("password").Comment("Password | 密码"),
		field.String("nickname").Nillable().Optional().Unique().Comment("Nickname | 昵称"),
	}
}

func (User) Mixin() []ent.Mixin {
	// status / created_at / updated_at / version / deleted_at
	return []ent.Mixin{
		mixins.NewDistributedIDMixin(func() int64 { return nrandom.SnowflakeId() }),
		mixins.StatusMixin{},
		mixins.TimeMixin{},
		mixins.OptimisticLockMixin{},
	}
}

func (User) Edges() []ent.Edge {
	return []ent.Edge{
		// one to many
		edge.To("metas", UserMeta.Type).
			Annotations(entsql.OnDelete(entsql.Cascade)),
		// one to many
		edge.To("roles", Role.Type),
		// one to many
		edge.To("socials", UserSocial.Type).
			Annotations(entsql.OnDelete(entsql.Cascade)),
		// one to many
		edge.To("departments", Department.Type),
		// one to many
		edge.To("token", Token.Type).
			Annotations(entsql.OnDelete(entsql.Cascade)),
		// one to one
		edge.To("loginRecord", LoginRecord.Type).
			Annotations(entsql.OnDelete(entsql.Cascade)).
			Unique(),
	}
}

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

func (User) Annotations() []schema.Annotation {
	return []schema.Annotation{
		entsql.WithComments(true),
		entsql.Annotation{Table: "sys_user"},
		schema.Comment("系统用户表"),
	}
}
