<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\RoleRequest;
use App\Http\Requests\PaginatedRequest;
use App\Services\Admin\Settings\RoleService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    public function __construct(
        private RoleService $service
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/roles/index', [
            'roles' => $this->service->paginated(...$request->validatedWithDefaults()),
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('admin/roles/create', [
            'permissions' => $this->service->getPermissionsByModule(),
        ]);
    }

    public function store(RoleRequest $request): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->store($request->validated()),
            'Role berhasil ditambahkan.',
            'admin.settings.roles.index'
        );
    }

    public function edit(Role $role): Response
    {
        return Inertia::render('admin/roles/edit', [
            'role' => $role->load('permissions'),
            'permissions' => $this->service->getPermissionsByModule(),
        ]);
    }

    public function update(RoleRequest $request, Role $role): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->update($role, $request->validated()),
            'Role berhasil diperbarui.',
            'admin.settings.roles.index'
        );
    }

    public function destroy(Role $role): RedirectResponse
    {
        $this->service->destroy($role);

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Role berhasil dihapus.']);

        return back();
    }
}
