<?php

namespace App\Http\Controllers\API\V1;

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

class ProductController extends Controller
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $perPage = $request->query('per_page', 15);
        $paginationType = $request->query('pagination', 'cursor');

        $query = Product::query()
            ->with('category')
            ->when($request->filled('category_id'), fn ($q) => $q->filterByCategory($request->category_id))
            ->when($request->filled(['min_price', 'max_price']), fn ($q) => $q->filterByPriceRange($request->min_price, $request->max_price))
            ->when($request->filled('search'), fn ($q) => $q->search($request->search))
            ->when($request->filled('sort_by'), fn ($q) => $q->sortBy($request->sort_by, $request->get('sort_direction', 'asc')))
            ->orderBy('id', 'desc');

        if ($paginationType === 'cursor') {
            $products = $query->cursorPaginate($perPage);

            return ProductResource::collection($products);
        }

        $products = $query->paginate($perPage);

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