<?php

namespace App\Http\Controllers\Admin\Developer;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Developer\UpdateRolePermissionsRequest;
use App\Services\Admin\Developer\RolePermissionService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;
use Spatie\Permission\Models\Role;

class RolePermissionController extends Controller
{
    public function __construct(
        private readonly RolePermissionService $service,
    ) {}

    public function index(): Response
    {
        return Inertia::render('admin/developer/roles/index', [
            'roles' => $this->service->roles(),
            'permissionGroups' => $this->service->groupedPermissions(),
        ]);
    }

    public function update(UpdateRolePermissionsRequest $request, Role $role): RedirectResponse
    {
        $this->service->updatePermissions($role, $request->validated('permissions'));

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Permission role berhasil diperbarui.']);

        return to_route('admin.developer.roles.index');
    }
}
