<?php

namespace Modules\ProductCompat\Entities\Enrichment\Providers;

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

/**
 * Looks up part numbers on the manufacturer's official site. Driven by a
 * per-brand URL template map in config:
 *   'official' => ['brand_urls' => ['acer' => 'https://.../search?q={query}', ...]]
 * Only runs for brands that have a configured template.
 */
class OfficialSiteProvider extends AbstractScrapeProvider
{
    public function key(): string
    {
        return 'official';
    }

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

    public function fetch(Product $product): EnrichmentResult
    {
        $map = array_change_key_case(config('productcompat.enrichment.official.brand_urls', []), CASE_LOWER);
        $brand = strtolower((string) optional($product->brand)->name);

        if ($brand === '' || empty($map[$brand])) {
            return EnrichmentResult::empty(['reason' => 'no official template for brand: ' . $brand]);
        }

        $url = $this->buildUrl($map[$brand], $product->name ?: $product->sku);
        $body = $this->fetchUrl($url);
        if ($body === null) {
            return EnrichmentResult::fail('fetch failed', ['url' => $url]);
        }

        $conf = (int) (config('productcompat.enrichment.confidence.official') ?? 70);
        $parts = array_map(function ($p) use ($conf) {
            $p['confidence'] = $conf;
            return $p;
        }, $this->parser->extractPartNumbersFromText($body));

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