<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\ProductResource;
use App\Models\Product;
use App\Models\Wishlist;
use App\Models\WishlistItem;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class WishlistController extends Controller
{
    private function getWishlist(Request $request): Wishlist
    {
        $user = $request->user('sanctum');
        $sessionId = $request->header('X-Wishlist-Session') ?: $request->input('session_id');

        if ($user) {
            return Wishlist::firstOrCreate(['user_id' => $user->id]);
        }

        if (!$sessionId) {
            $sessionId = md5(microtime() . $request->ip());
        }

        return Wishlist::firstOrCreate(['session_id' => $sessionId]);
    }

    public function index(Request $request): JsonResponse
    {
        $wishlist = $this->getWishlist($request);
        $productIds = $wishlist->items()->pluck('product_id')->toArray();

        $products = Product::with(['category', 'images', 'primaryImage'])
            ->whereIn('id', $productIds)
            ->get();

        return response()->json([
            'success' => true,
            'session_id' => $wishlist->session_id,
            'data' => ProductResource::collection($products),
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
        ]);

        $wishlist = $this->getWishlist($request);
        $productId = $request->input('product_id');

        WishlistItem::firstOrCreate([
            'wishlist_id' => $wishlist->id,
            'product_id' => $productId,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Product added to wishlist',
            'session_id' => $wishlist->session_id,
        ]);
    }

    public function destroy(Request $request, int $productId): JsonResponse
    {
        $wishlist = $this->getWishlist($request);
        WishlistItem::where('wishlist_id', $wishlist->id)
            ->where('product_id', $productId)
            ->delete();

        return response()->json([
            'success' => true,
            'message' => 'Product removed from wishlist',
        ]);
    }
}
