<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class RoleResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'name' => $this->name,
            'label' => $this->label ?? $this->name,
            'description' => $this->description,
            'level' => $this->level,
            'is_system' => (bool) $this->is_system,
            'is_active' => (bool) $this->is_active,
            'users_count' => $this->whenCounted('users'),
            'permissions_count' => $this->whenCounted('permissionScopes'),
            // permission key => scope, present when the caller asked for detail.
            'permissions' => $this->whenLoaded(
                'permissionScopes',
                fn () => $this->permissionScopes
                    ->filter(fn ($grant) => $grant->permission !== null)
                    ->mapWithKeys(fn ($grant) => [$grant->permission->name => $grant->scope->value])
            ),
            'created_at' => $this->created_at?->toIso8601String(),
            'updated_at' => $this->updated_at?->toIso8601String(),
        ];
    }
}
