<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class WishlistController extends Controller
{
    public function index(): View
    {
        // A wishlisted product can later be deleted (or soft-deleted) from
        // the catalog — whereHas excludes those orphaned rows instead of
        // handing a null product down to the view.
        $products = auth()->user()->wishlists()
            ->whereHas('product')
            ->with([
                'product' => fn ($q) => $q->withRatings(),
                'product.primaryImage',
                'product.category',
                'product.variants.inventory',
            ])
            ->latest()
            ->paginate(12);

        return view('frontend.wishlist.index', compact('products'));
    }

    public function toggle(Request $request, Product $product): RedirectResponse|JsonResponse
    {
        $wishlist = auth()->user()->wishlists()->where('product_id', $product->id)->first();

        if ($wishlist) {
            $wishlist->delete();
            $message = 'Removed from your wishlist.';
            $action = 'removed';
        } else {
            auth()->user()->wishlists()->create(['product_id' => $product->id]);
            $message = 'Added to your wishlist.';
            $action = 'added';
        }

        if ($request->wantsJson()) {
            return response()->json([
                'message' => $message,
                'action' => $action,
                // Same whereHas('product') as index() — keeps the badge in
                // sync with what the wishlist page will actually show.
                'wishlistCount' => auth()->user()->wishlists()->whereHas('product')->count(),
            ]);
        }

        return back()->with('success', $message);
    }
}
