<?php

namespace App\Services\Menu\Adapters;

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

        if (is_array($url)) {
            $candidate = $url[$locale] ?? null;
            if (! $candidate) {
                $candidate = is_array($url) && count($url) > 0 ? reset($url) : null;
            }
            $url = $candidate;
        }

        if (! is_string($url) || $url === '') return null;
        if (! $this->isSafeUrl($url)) return null;

        // Slug-locale-lock: admin'in girdiği hardcoded `/pricing`-tipi
        // path'ler, registered route name'e eşleşiyorsa locale variant'ına
        // swap edilir (örn TR locale'de `/pricing` → `/fiyatlar`). Tek
        // hardcoded URL ile locale-aware menu/content sağlar.
        if (str_starts_with($url, '/') && function_exists('localized_url')) {
            $url = localized_url($url);
        }

        return $url;
    }

    public function isValid(array $linkTarget): bool
    {
        $url = $linkTarget['url'] ?? null;
        if (! $url) return false;

        if (is_array($url)) {
            foreach ($url as $value) {
                if (! is_string($value) || ! $this->isSafeUrl($value)) return false;
            }
            return count($url) > 0;
        }

        return is_string($url) && $this->isSafeUrl($url);
    }

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

    private function isSafeUrl(string $url): bool
    {
        if ($url === '') return false;
        if (str_starts_with($url, '/') || str_starts_with($url, '#')) return true;
        if (preg_match('~^https?://~i', $url)) return true;
        return false;
    }
}
