<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\ArticleResource;
use App\Http\Resources\CategoryResource;
use App\Http\Resources\ProductResource;
use App\Models\Article;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function search(Request $request): JsonResponse
    {
        $q = trim($request->input('q', ''));

        if (empty($q)) {
            return response()->json([
                'success' => true,
                'data' => [
                    'products' => [],
                    'categories' => [],
                    'articles' => [],
                ],
            ]);
        }

        $products = Product::with(['category', 'images', 'primaryImage'])
            ->where('status', 'published')
            ->where(function ($query) use ($q) {
                $query->where('name', 'like', "%{$q}%")
                    ->orWhere('sku', 'like', "%{$q}%")
                    ->orWhere('material', 'like', "%{$q}%")
                    ->orWhere('finish', 'like', "%{$q}%")
                    ->orWhere('short_description', 'like', "%{$q}%");
            })
            ->limit(6)
            ->get();

        $categories = Category::where('status', 'published')
            ->where('name', 'like', "%{$q}%")
            ->limit(4)
            ->get();

        $articles = Article::where('status', 'published')
            ->where(function ($query) use ($q) {
                $query->where('title', 'like', "%{$q}%")
                    ->orWhere('excerpt', 'like', "%{$q}%");
            })
            ->limit(3)
            ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'products' => ProductResource::collection($products),
                'categories' => CategoryResource::collection($categories),
                'articles' => ArticleResource::collection($articles),
            ],
        ]);
    }
}
