package models

import (
	"time"

	"gorm.io/gorm"
)

// 用户的自定义权限关联表
type MgtLinkUserPmn struct {
	UserId    uint      `gorm:"column:user_id;primaryKey" json:"user_id"`                     // 用户ID
	AppId     uint      `gorm:"column:app_id;primaryKey" json:"app_id"`                       // 应用ID
	PmnId     uint      `gorm:"column:pmn_id;primaryKey" json:"pmn_id"`                       // 权限ID
	CreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at,omitempty"` // 创建时间
}

func (MgtLinkUserPmn) TableName() string {
	return "mgt_link_user_pmn"
}

// func init() {
// 	database.AppendMigrate(&MgtLinkUserPmn{})
// }

// AfterDelete钩子：仅当该用户在该应用下不再拥有任何权限时，移除用户-应用关联
func (l *MgtLinkUserPmn) AfterDelete(tx *gorm.DB) error {
	var count int64
	if err := tx.Model(&MgtLinkUserPmn{}).
		Where("app_id = ? AND user_id = ?", l.AppId, l.UserId).
		Count(&count).Error; err != nil {
		return err
	}
	if count == 0 {
		if err := tx.Where("app_id = ? AND user_id = ?", l.AppId, l.UserId).
			Delete(&MgtLinkUserApp{}).Error; err != nil {
			return err
		}
	}
	return nil
}
