package models

import (
	"time"

	"gorm.io/gorm"
)

// Role 角色模型
type Role struct {
	ID          uint         `json:"id" gorm:"primaryKey;column:id"`
	Name        string       `json:"name" gorm:"column:name;uniqueIndex"`
	Description string       `json:"description" gorm:"column:description"`
	Permissions []Permission `json:"permissions,omitempty" gorm:"many2many:role_permissions;joinForeignKey:role_id;joinReferences:permission_id"`
	CreatedAt   int64        `json:"createdAt" gorm:"column:created_at"`
	UpdatedAt   int64        `json:"updatedAt" gorm:"column:updated_at"`
	DeletedAt   int64        `json:"deletedAt" gorm:"column:deleted_at;default:0"`
}

// TableName 指定表名
func (Role) TableName() string {
	return "roles"
}

// BeforeCreate 创建前钩子
func (r *Role) BeforeCreate(tx *gorm.DB) error {
	now := time.Now().Unix()
	if r.CreatedAt == 0 {
		r.CreatedAt = now
	}
	if r.UpdatedAt == 0 {
		r.UpdatedAt = now
	}
	if r.DeletedAt == 0 {
		r.DeletedAt = 0
	}
	return nil
}

// BeforeUpdate 更新前钩子
func (r *Role) BeforeUpdate(tx *gorm.DB) error {
	r.UpdatedAt = time.Now().Unix()
	return nil
}

// RoleResponse 角色响应模型
type RoleResponse struct {
	ID          uint                 `json:"id"`
	Name        string               `json:"name"`
	Description string               `json:"description"`
	Permissions []PermissionResponse `json:"permissions,omitempty"`
	CreatedAt   string               `json:"createdAt"`
	UpdatedAt   string               `json:"updatedAt"`
}
