<?php

namespace App\Helpers;

use App\Models\Wishlist;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;

class ProductHelper
{
    /**
     * Get wishlist product IDs for the authenticated user
     * Cached for 5 minutes per user
     */
    public static function getWishlistProductIds(?int $userId = null): Collection
    {
        if (!$userId && !auth()->check()) {
            return collect([]);
        }

        $userId = $userId ?? auth()->id();

        try {
            return Cache::remember("wishlist_product_ids.{$userId}", 300, function () use ($userId) {
                return Wishlist::where('user_id', $userId)
                    ->pluck('product_id');
            });
        } catch (\Illuminate\Database\QueryException $e) {
            // If table doesn't exist, return empty collection
            if (str_contains($e->getMessage(), "doesn't exist")) {
                return collect([]);
            }
            throw $e;
        }
    }

    /**
     * Check if products are in wishlist
     * Returns array of product_id => boolean
     */
    public static function getWishlistStatus(array|Collection $productIds, ?int $userId = null): array
    {
        if (!$userId && !auth()->check()) {
            return array_fill_keys(
                is_array($productIds) ? $productIds : $productIds->toArray(),
                false
            );
        }

        $userId = $userId ?? auth()->id();
        $productIds = is_array($productIds) ? $productIds : $productIds->toArray();

        $wishlistProductIds = static::getWishlistProductIds($userId);

        $status = [];
        foreach ($productIds as $productId) {
            $status[$productId] = $wishlistProductIds->contains($productId);
        }

        return $status;
    }
}

