<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Items\Item;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ItemApiController extends Controller
{
    /**
     * 품목 검색 (datalist 자동완성용)
     */
    public function search(Request $request): JsonResponse
    {
        $tenantId = session('selected_tenant_id');
        $query = $request->input('q', '');

        $items = Item::query()
            ->where('tenant_id', $tenantId)
            ->where('is_active', true)
            ->when($query, function ($q) use ($query) {
                $q->where(function ($sub) use ($query) {
                    $sub->where('name', 'like', "%{$query}%")
                        ->orWhere('code', 'like', "%{$query}%");
                });
            })
            ->when($request->input('item_type'), function ($q, $types) {
                $q->whereIn('item_type', explode(',', $types));
            })
            ->when($request->input('ids'), function ($q, $ids) {
                $q->whereIn('id', explode(',', $ids));
            })
            ->orderBy('name')
            ->limit(30)
            ->get(['id', 'code', 'name', 'item_type', 'unit']);

        return response()->json([
            'success' => true,
            'data' => $items,
        ]);
    }
}
