<?php

namespace App\Http\Controllers\Api\V1\Product\Search;

use App\Http\Controllers\Api\V1\Product\Resources\ProductMediaResource;
use App\Http\Controllers\Controller;
use App\Models\Ecommerce\Product\Product\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ProductSearchController extends Controller
{
    /**
     * Search product via barcode
     */
    public function index(Request $request): JsonResponse
    {
        $request->validate([
            'q' => ['required', 'string', 'max:255'],
        ]);

        $searchQuery = $request->input('q');

        $products = Product::with(['brand', 'media'])
            ->where(function ($query) use ($searchQuery) {
                if (is_numeric($searchQuery)) {
                    $query->where('products.id', intval($searchQuery));
                }

                $query
                    ->orWhere('products.name', '~*', $searchQuery)
                    ->orWhere('products.sku', '~*', $searchQuery)
                    ->orWhere('products.barcode', '~*', $searchQuery);
            })
            ->when($request->isNotFilled('internal'), function ($query) {
                $query->where('products.is_visible', true)
                    ->where('products.parent_id', null)
                    ->where('products.stock', '>', 0);
            })
            ->limit(40)
            ->get();

        return response()->rest(
            $products->map(fn ($product) => [
                'id' => $product->id,
                'name' => $product->fullName,
                'stock' => $product->stock,
                'cost_amount' => $product->cost_amount,
                'price_amount' => $product->price_amount,
                'brand' => [
                    'id' => $product->brand?->id,
                    'name' => $product->brand?->name,
                ],
                'thumbnail' => $product->thumbnail(),
                'media' => ProductMediaResource::collection($product->media),
            ])
        );
    }
}
