package models

import (
	"github.com/veypi/vigo"
	"gorm.io/gorm"
)

// salt for user user password gen aes code
// salt 32 hex / 16 byte / 128 bit
// code 64 hex / 32 byte / 256 bit
type User struct {
	vigo.Model
	Username string `json:"username" gorm:"type:varchar(100);unique;default:not null"  src:"json" desc:"用户名"`
	Nickname string `json:"nickname" gorm:"type:varchar(100)"  src:"json" desc:"昵称"`
	Icon     string `json:"icon"  src:"json" desc:"头像"`

	Email  string `json:"email" gorm:"unique;type:varchar(64);null;default:null"  src:"json" desc:"邮箱"`
	Phone  string `json:"phone" gorm:"type:varchar(64);unique;null;default:null"  src:"json" desc:"手机号"`
	Region string `json:"region" gorm:"type:varchar(32);default:null"  src:"json" desc:"地区"`

	Status uint `json:"status"  src:"json" desc:"状态"`

	Salt string `json:"-" gorm:"type:varchar(32)"`
	Code string `json:"-" gorm:"type:varchar(64)"  src:"json" desc:"代码"`
}

type UserRole struct {
	vigo.Model
	UserID string `json:"user_id" src:"path@user_id" desc:"用户ID"`
	User   *User  `json:"-" gorm:"foreignKey:UserID;references:ID"`

	RoleID string `json:"role_id" src:"json" desc:"角色ID"`
	Role   *Role  `json:"-" gorm:"foreignKey:RoleID;references:ID"`

	AppID string `json:"app_id" src:"json" desc:"应用ID"`
	App   *App   `json:"-" gorm:"foreignKey:AppID;references:ID"`

	Status string `json:"status"`
}

func (m *UserRole) AfterCreate(tx *gorm.DB) error {
	return tx.Model(&Role{}).Where("id = ?", m.RoleID).Update("user_count", gorm.Expr("user_count + ?", 1)).Error
}
