<?php

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

use App\Http\Controllers\Api\V1\Product\Resources\Review\ProductReviewResource;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Product\Review\ProductReviewStore;
use App\Models\Ecommerce\Product\Product\Product;
use Illuminate\Http\JsonResponse;

class ProductReviewController extends Controller
{
    /**
     * Product reviews (index)
     */
    public function index(Product $product): JsonResponse
    {
        return response()->rest(
            ProductReviewResource::collection(
                $product->reviews()
                    ->where('is_visible', true)
                    ->orderBy('is_recommended')
                    ->get()
            )
        );
    }

    /**
     * (*) Product reviews (store)
     */
    public function store(ProductReviewStore $request, Product $product): JsonResponse
    {
        $product->reviews()->create([
            'user_id' => auth()->id(),
            ...$request->validated(),
        ]);

        return response()->rest(message: 'Review added successfully', code: 201);
    }
}
