<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\SearchRequest;
use App\Http\Resources\ProductResource;
use App\Models\Product;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

final class SearchController extends Controller
{
    public function search(SearchRequest $request): AnonymousResourceCollection
    {
        $query = $request->validated('q', '');
        $perPage = (int) $request->validated('per_page', 20);

        $searchQuery = Product::search($query);

        // Apply category filter
        if ($request->validated('category')) {
            $searchQuery->where('category_id', $request->validated('category'));
        }

        // Apply source filter
        if ($request->validated('source')) {
            $searchQuery->where('source', $request->validated('source'));
        }

        // Apply price range filters
        if ($request->validated('price_min')) {
            $searchQuery->where('price', '>=', (float) $request->validated('price_min'));
        }

        if ($request->validated('price_max')) {
            $searchQuery->where('price', '<=', (float) $request->validated('price_max'));
        }

        // Apply sorting
        $sort = $request->validated('sort', 'relevance');
        if ($sort === 'price_asc') {
            $searchQuery->orderBy('price', 'asc');
        } elseif ($sort === 'price_desc') {
            $searchQuery->orderBy('price', 'desc');
        } elseif ($sort === 'sales') {
            $searchQuery->orderBy('sales_180day', 'desc');
        } elseif ($sort === 'clicks') {
            $searchQuery->orderBy('clicks', 'desc');
        }

        $results = $searchQuery->paginate($perPage);

        // Eager load category relationship to prevent N+1
        $results->load('category');

        return ProductResource::collection($results);
    }
}
