// internal/models/role.go
package models

import (
	"time"

	"gorm.io/gorm"
)

// Role represents a user role in the system
type Role struct {
	ID          uint           `gorm:"primaryKey" json:"id"`
	Name        string         `gorm:"type:varchar(50);uniqueIndex;not null" json:"name"`
	Description string         `gorm:"type:text" json:"description"`
    
    // ✅ Tambahkan relasi Permissions
	Permissions []Permission   `gorm:"many2many:role_permissions;" json:"permissions,omitempty"`

	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
	DeletedAt   gorm.DeletedAt `gorm:"index" json:"-"`
    
	Users       []User         `gorm:"foreignKey:RoleID" json:"users,omitempty"`
}

// TableName specifies the table name for Role model
func (Role) TableName() string {
	return "roles"
}

// Role constants
const (
	RoleAdmin   = "admin"
	RoleManager = "manager"
	RoleUser    = "user"
)

// GetRoleID returns the ID for a given role name
func GetRoleID(db *gorm.DB, roleName string) (uint, error) {
	var role Role
	if err := db.Where("name = ?", roleName).First(&role).Error; err != nil {
		return 0, err
	}
	return role.ID, nil
}

// IsValidRole checks if a role name is valid
func IsValidRole(roleName string) bool {
	validRoles := []string{RoleAdmin, RoleManager, RoleUser}
	for _, r := range validRoles {
		if r == roleName {
			return true
		}
	}
	return false
}