<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\BaseResource;
use App\Services\ItemDataService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Item API
 *
 * Endpoint untuk pencarian dan pengambilan data item game Perfect World.
 * Tidak memerlukan autentikasi token.
 */
final class ItemController extends Controller
{
    public function __construct(
        protected ItemDataService $itemService
    ) {}

    /**
     * Get item by ID.
     */
    public function show(string $id): JsonResponse
    {
        $itemData = $this->itemService->getItemWithIcon($id);

        if (! $itemData['name']) {
            return BaseResource::makeEnvelope(
                resource: null,
                success: false,
                error: "Item with ID {$id} does not exist",
                status: 404,
            );
        }

        return BaseResource::makeEnvelope(resource: $itemData);
    }

    /**
     * Search items.
     *
     * @queryParam q string required Kata kunci pencarian. Example: `sword`
     */
    public function search(Request $request): JsonResponse
    {
        $query = $request->input('q', '');

        if (strlen($query) < 1) {
            return BaseResource::makeEnvelope(resource: []);
        }

        $items = $this->itemService->searchItems($query, 20);

        return BaseResource::makeEnvelope(resource: $items);
    }
}
