<?php

namespace App\Services\Menu\Adapters;

use App\Models\Product;

class ProductAdapter implements LinkAdapter
{
    public function resolve(array $linkTarget, string $locale, array $context = []): ?string
    {
        $productId = $linkTarget['product_id'] ?? null;
        if (! $productId) return null;

        $product = $context['product'] ?? null;
        if (! $product || ! ($product instanceof Product) || $product->id !== (int) $productId) {
            $product = Product::find($productId);
        }
        if (! $product || ! $product->slug) return null;

        try {
            return route('store.products.show', $product->slug);
        } catch (\Throwable $e) {
            return null;
        }
    }

    public function isValid(array $linkTarget): bool
    {
        $id = $linkTarget['product_id'] ?? null;
        return is_numeric($id) && Product::whereKey($id)->exists();
    }

    public function searchable(): bool { return true; }
}
