<?php

namespace MintyPHP\Module\Bookmarks\Providers;

use MintyPHP\App\Module\Contracts\SearchResourceProvider;

/**
 * Provides the bookmarks search resource for the global search.
 *
 * Bookmarks are user-scoped: the SQL uses {{userId}} so only
 * the current user's bookmarks are searched.
 */
final class BookmarksSearchProvider implements SearchResourceProvider
{
    public function resources(): array
    {
        return [
            'bookmarks' => [
                'label' => t('Bookmarks'),
                'permission' => '',
                'count_sql' => "SELECT COUNT(*) FROM user_bookmarks WHERE user_id = {{userId}} AND (name LIKE ? ESCAPE '\\\\' OR url LIKE ? ESCAPE '\\\\')",
                'preview_sql' => "SELECT id, name, url FROM user_bookmarks WHERE user_id = {{userId}} AND (name LIKE ? ESCAPE '\\\\' OR url LIKE ? ESCAPE '\\\\') ORDER BY sort_order ASC LIMIT ?",
                'result_sql' => "SELECT id, name, url FROM user_bookmarks WHERE user_id = {{userId}} AND (name LIKE ? ESCAPE '\\\\' OR url LIKE ? ESCAPE '\\\\') ORDER BY sort_order ASC",
            ],
        ];
    }

    public function mapResultItem(string $resourceKey, array $row): ?array
    {
        if ($resourceKey !== 'bookmarks') {
            return null;
        }

        $name = trim((string) ($row['name'] ?? ''));
        $url = trim((string) ($row['url'] ?? ''));

        if ($name === '') {
            return null;
        }

        return [
            'title' => $name,
            'subtitle' => $url,
            'url' => $url !== '' ? $url : '#',
            'icon' => 'bi-bookmark-star',
        ];
    }

    public function listUrl(string $resourceKey, string $encodedSearch): string
    {
        return '';
    }
}
