<?php

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

use App\Http\Controllers\Api\V1\Product\Resources\ProductResource;
use App\Http\Controllers\Controller;
use App\Models\Ecommerce\Product\Product\Product;
use App\Repositories\Ecommerce\Product\ProductRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class ProductRelatedController extends Controller
{
    /**
     * Related products (index)
     */
    public function index(Product $product): JsonResponse
    {
        $products = DB::table('category_product')
            ->select('category_product.product_id')
            ->whereIn('category_product.category_id', (function ($query) use ($product) {
                $query->from('category_product')
                    ->select('category_id')
                    ->distinct('category_id')
                    ->where('product_id', '=', $product->id);
            }))
            ->limit(12)
            ->orderByRaw('RANDOM()')
            ->pluck('category_product.product_id')
            ->unique();

        return response()->rest(
            ProductResource::collection(
                ProductRepository::make(request())
                    ->applyBasicQueries()
                    ->whereIntegerInRaw('id', $products->toArray())
                    ->get()
            )
        );
    }
}
