<?php

namespace App\Modules\Admin\Tenancy\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\DTOs\ModuleData;
use App\Modules\Admin\Tenancy\Models\Module;
use App\Modules\Admin\Tenancy\Requests\StoreModuleRequest;
use App\Modules\Admin\Tenancy\Requests\UpdateModuleRequest;
use App\Modules\Admin\Tenancy\Services\ModuleService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use RuntimeException;

class ModuleController extends Controller
{
    public function __construct(
        private readonly ModuleService $service,
    ) {}

    public function index(): View
    {
        return view('pages.admin.modules.index', [
            'modules' => $this->service->list(),
        ]);
    }

    public function create(): View
    {
        return view('pages.admin.modules.create');
    }

    public function store(StoreModuleRequest $request): RedirectResponse
    {
        $this->service->create(ModuleData::fromValidated($request->validated()));

        return redirect()
            ->route('admin.modules.index')
            ->with('status', __('modules.created'));
    }

    public function edit(Module $module): View
    {
        return view('pages.admin.modules.edit', ['module' => $module]);
    }

    public function update(UpdateModuleRequest $request, Module $module): RedirectResponse
    {
        $this->service->update($module, ModuleData::fromValidated($request->validated()));

        return redirect()
            ->route('admin.modules.index')
            ->with('status', __('modules.updated'));
    }

    public function destroy(Module $module): RedirectResponse
    {
        try {
            $this->service->delete($module);
        } catch (RuntimeException $exception) {
            return redirect()
                ->route('admin.modules.index')
                ->with('error', $exception->getMessage());
        }

        return redirect()
            ->route('admin.modules.index')
            ->with('status', __('modules.deleted'));
    }
}
