<?php

namespace App\Http\Controllers\Frontend;

use App\Enums\ReviewStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\Frontend\ReviewRequest;
use App\Models\Order;
use App\Models\Product;
use App\Models\Review;
use Illuminate\Http\RedirectResponse;

class ReviewController extends Controller
{
    public function store(ReviewRequest $request, Product $product): RedirectResponse
    {
        // Verified-purchase badge, when an eligible order already exists —
        // reviewing doesn't require one, since orders aren't live until
        // Step 12.
        $orderId = Order::where('user_id', auth()->id())
            ->whereHas('items', fn ($q) => $q->where('product_id', $product->id))
            ->latest()
            ->value('id');

        Review::updateOrCreate(
            ['product_id' => $product->id, 'user_id' => auth()->id()],
            [
                ...$request->validated(),
                'order_id' => $orderId,
                'status' => ReviewStatus::Pending,
            ]
        );

        return back()->with('success', "Thanks for your review — it'll appear once approved.");
    }
}
