<?php

namespace Modules\ProductCompat\Entities\Enrichment\Providers;

use App\Product;
use Modules\ProductCompat\Entities\Enrichment\EnrichmentResult;

/**
 * Falls back to high-trust aggregator sites. Driven by a list of search URL
 * templates in config:
 *   'trusted' => ['search_urls' => ['https://aggregator.tld/search?q={query}', ...]]
 * Tries each in order until one yields candidates.
 */
class TrustedSiteProvider extends AbstractScrapeProvider
{
    public function key(): string
    {
        return 'trusted';
    }

    public function isAvailable(): bool
    {
        return ! empty(config('productcompat.enrichment.trusted.search_urls', []));
    }

    public function fetch(Product $product): EnrichmentResult
    {
        $templates = config('productcompat.enrichment.trusted.search_urls', []);
        $query = trim(implode(' ', array_filter([optional($product->brand)->name, $product->name])));
        $conf = (int) (config('productcompat.enrichment.confidence.trusted') ?? 55);

        $tried = [];
        foreach ($templates as $tpl) {
            $url = $this->buildUrl($tpl, $query ?: $product->sku);
            $tried[] = $url;
            $body = $this->fetchUrl($url);
            if ($body === null) {
                continue;
            }

            $parts = array_map(function ($p) use ($conf) {
                $p['confidence'] = $conf;
                return $p;
            }, $this->parser->extractPartNumbersFromText($body));

            if (! empty($parts)) {
                return new EnrichmentResult(true, ['part_numbers' => $parts], ['url' => $url, 'matched' => count($parts)]);
            }
        }

        return EnrichmentResult::empty(['tried' => $tried]);
    }
}
