<?php

namespace App\Http\Controllers\Api\V1\Showroom;

use App\Http\Controllers\Controller;
use App\Models\Item;
use App\Scopes\StoreScope;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function search(Request $request)
    {
        $queryText = trim((string) $request->query('q', $request->query('barcode', '')));
        $limit = min(max((int) $request->query('limit', 20), 1), 50);

        $items = Item::withoutGlobalScopes()
            ->withoutGlobalScope(StoreScope::class)
            ->when($queryText !== '', function ($query) use ($queryText) {
                $query->where(function ($inner) use ($queryText) {
                    if (is_numeric($queryText)) {
                        $inner->orWhere('id', (int) $queryText);
                    }
                    $inner->orWhere('name', 'like', "%{$queryText}%")
                        ->orWhere('slug', 'like', "%{$queryText}%");
                });
            })
            ->latest('id')
            ->limit($limit)
            ->get();

        return response()->json($items->map(fn ($item) => [
            'id' => $item->id,
            'name' => $item->name,
            'price' => (float) $item->price,
            'stock' => (int) ($item->stock ?? 0),
            'image_full_url' => $item->image_full_url,
            'variations' => is_array($item->variations) ? $item->variations : json_decode($item->variations ?: '[]', true),
            'store_id' => $item->store_id,
            'module_id' => $item->module_id,
        ]));
    }
}
