<?php

namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Concerns\FlashesEntityMessage;
use App\Http\Controllers\Concerns\ParsesDataTableQuery;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\System\RoleRequest;
use App\Services\System\RoleService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    use FlashesEntityMessage, ParsesDataTableQuery;

    public function __construct(
        private readonly RoleService $roleService,
    ) {}

    public function index(Request $request): Response
    {
        $tableQuery = $this->parseDataTableQuery($request);

        return Inertia::render('admin/system/roles/Index', [
            'roles' => $this->roleService->paginateForIndex($tableQuery),
            'filters' => $this->dataTableFilters($tableQuery),
        ]);
    }

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

    public function store(RoleRequest $request): RedirectResponse
    {
        $this->roleService->create($request->validated());

        $this->flashCreated('Role');

        return redirect()->route('admin.system.roles.index');
    }

    public function edit(Role $role): Response
    {
        return Inertia::render('admin/system/roles/Edit', [
            ...$this->roleService->findForEdit($role),
            'permissions' => $this->roleService->permissionOptions(),
        ]);
    }

    public function update(RoleRequest $request, Role $role): RedirectResponse
    {
        $this->roleService->update($role, $request->validated());

        $this->flashUpdated('Role');

        return redirect()->route('admin.system.roles.index');
    }

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

        $this->flashDeleted('Role');

        return redirect()->route('admin.system.roles.index');
    }
}
