<?php

namespace Modules\MedOrganization\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * ABAC rule row (role × entity × predicate → allow/deny), evaluated by
 * Services\MedAccess. role_id = concrete Spatie role; role_key = predefined
 * medical role key resolved as `{key}#{business_id}`.
 */
class OrgAccessRule extends Model
{
    protected $table = 'org_access_rules';

    protected $guarded = ['id'];

    protected $casts = [
        'rule_value' => 'array',
        'is_active'  => 'boolean',
    ];

    public const RULE_KEYS = ['only_assigned', 'entity_ability', 'field_group'];

    public function role()
    {
        return $this->belongsTo(\Spatie\Permission\Models\Role::class, 'role_id');
    }

    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
}
