<?php

namespace App\Http\Controllers;

use App\Models\Printer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PrinterSearchController extends Controller
{
    public function search(Request $request): JsonResponse
    {
        $request->validate(['q' => ['nullable', 'string', 'max:100']]);
        $q = trim((string) $request->query('q', ''));

        if ($q === '') {
            return response()->json(['results' => []]);
        }

        $printers = Printer::query()
            ->with('client')
            ->where(function ($query) use ($q) {
                foreach (preg_split('/\s+/', $q, -1, PREG_SPLIT_NO_EMPTY) as $term) {
                    $query->where(function ($sub) use ($term) {
                        $sub->where('manufacturer', 'like', "%{$term}%")
                            ->orWhere('model', 'like', "%{$term}%")
                            ->orWhere('serial_number', 'like', "%{$term}%")
                            ->orWhereHas('client', fn ($c) => $c->where('name', 'like', "%{$term}%"));
                    });
                }
            })
            ->orderBy('model')
            ->limit(10)
            ->get();

        return response()->json([
            'results' => $printers->map(fn (Printer $p) => [
                'id' => $p->id,
                'label' => trim($p->manufacturer.' '.$p->model).' · '.$p->serial_number.' · '.($p->client?->name ?? ''),
                'url' => route('book.show', $p->qr_token),
            ])->all(),
        ]);
    }
}
