<?php

namespace App\Modules\Inventory\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Inventory\DTOs\ItemWriteData;
use App\Modules\Inventory\Models\Item;
use App\Modules\Inventory\Models\ItemCategory;
use App\Modules\Inventory\Requests\StoreItemRequest;
use App\Modules\Inventory\Services\ItemManagementService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

final class ItemCreateController extends Controller
{
    public function __construct(
        private readonly ItemManagementService $management,
    ) {}

    public function create(): View
    {
        $this->authorize('create', Item::class);

        return view('pages.inventory.items.create', [
            'categories' => ItemCategory::query()->orderBy('code')->get(['id', 'code', 'name']),
        ]);
    }

    public function store(StoreItemRequest $request): RedirectResponse
    {
        $item = $this->management->store(ItemWriteData::fromValidated($request->validated()));

        return redirect()
            ->route('inventory.items.show', $item)
            ->with('status', __('inventory.items.flash.created'));
    }
}
