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"
	"git.noahlan.cn/noahlan/ntool/nstd/tea"
)

type Token struct {
	ent.Schema
}

func (Token) Fields() []ent.Field {
	return []ent.Field{
		field.Int64("user_id").
			Annotations(entsql.Annotation{Incremental: tea.Bool(false)}).
			Comment("User's ID | 用户ID"),
		field.String("token_type").Comment("Token type | 凭证类型 [Bearer]"),
		field.String("access_token").Comment("AccessToken | AccessToken 字符串"),
		field.String("refresh_token").Comment("RefreshToken | RefreshToken 字符串"),
		field.String("source").Comment("Source | Token来源，PCWeb/WechatMini/AlipayMini"),
		field.Time("expired_at").SchemaType(map[string]string{dialect.MySQL: "datetime"}).Comment("Expire Time | 过期时间"),
	}
}

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

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

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

func (Token) Annotations() []schema.Annotation {
	return []schema.Annotation{
		entsql.WithComments(true),
		entsql.Annotation{Table: "sys_token"},
		schema.Comment("Token表"),
	}
}
