<?php

namespace App\Http\Controllers;

use App\Models\ProductReview;
use App\Models\Product;
use Illuminate\Http\Request;

class ReviewController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function store(Request $request, Product $product)
    {
        $validated = $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'title' => 'required|string|max:255',
            'comment' => 'required|string|max:1000',
        ]);

        ProductReview::updateOrCreate(
            ['product_id' => $product->id, 'user_id' => auth()->id()],
            array_merge($validated, ['user_id' => auth()->id()])
        );

        return back()->with('success', 'Review submitted successfully!');
    }

    public function destroy(ProductReview $review)
    {
        $this->authorize('delete', $review);
        $review->delete();
        return back()->with('success', 'Review deleted');
    }
}
