<?php

namespace App\Http\Controllers\Api\Users;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class RoleIndexController extends Controller
{
    public function __invoke(): JsonResponse
    {
        app(PermissionRegistrar::class)->setPermissionsTeamId(request()->user()->tenant_id);

        $rows = Role::query()
            ->orderBy('name')
            ->get()
            ->map(fn (Role $role) => [
                'id' => $role->id,
                'name' => $role->name,
                'permissionsCount' => $role->permissions()->count(),
                'permissions' => $role->permissions()->orderBy('name')->pluck('name')->values()->all(),
            ])
            ->values();

        app(PermissionRegistrar::class)->setPermissionsTeamId(null);

        return response()->json(['data' => $rows]);
    }
}
