<?php

namespace App\Models;

use App\Support\Authorization\PermissionCatalog;
use Illuminate\Database\Eloquent\Builder;
use Spatie\Permission\Models\Role as SpatieRole;

class Role extends SpatieRole
{
    protected $fillable = [
        'name',
        'code',
        'organization_id',
        'guard_name',
        'is_system',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'organization_id' => 'integer',
            'is_system' => 'boolean',
            'is_active' => 'boolean',
        ];
    }

    public function organization()
    {
        return $this->belongsTo(Organization::class);
    }

    public function scopePlatform(Builder $query): Builder
    {
        return $query->whereNull('organization_id');
    }

    public function scopeForOrganization(Builder $query, int $organizationId): Builder
    {
        return $query->where('organization_id', $organizationId);
    }

    public function scopeCustom(Builder $query): Builder
    {
        return $query->where('is_system', false);
    }

    public function permissionCount(): int
    {
        return $this->permissions()->count();
    }

    public function permissionsMap(string $panel): array
    {
        return PermissionCatalog::permissionMatrixForRole($this, $panel);
    }
}
