<?php

namespace Modules\ProductCompat\Entities\Enrichment\Providers;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Modules\ProductCompat\Entities\Enrichment\EnrichmentProvider;
use Modules\ProductCompat\Entities\Services\CustomFieldParser;

/**
 * Shared HTTP fetch + cache + part-number extraction for the web-scraping
 * providers. Best-effort and ToS/robots-sensitive — kept disabled until URL
 * templates are configured, and always writes low-confidence/needs_review data.
 */
abstract class AbstractScrapeProvider implements EnrichmentProvider
{
    protected CustomFieldParser $parser;

    public function __construct(?CustomFieldParser $parser = null)
    {
        $this->parser = $parser ?? new CustomFieldParser();
    }

    /**
     * GET a URL with the configured UA/timeout, cached for cache_ttl_minutes.
     * Returns the body or null on failure.
     */
    protected function fetchUrl(string $url): ?string
    {
        $ttl = (int) config('productcompat.enrichment.cache_ttl_minutes', 1440);
        $ua  = config('productcompat.enrichment.user_agent', 'ProductCompatBot/1.0');
        $timeout = (int) config('productcompat.enrichment.timeout', 15);

        return Cache::remember('pc_enrich:' . md5($url), now()->addMinutes($ttl), function () use ($url, $ua, $timeout) {
            try {
                $resp = Http::timeout($timeout)->withHeaders(['User-Agent' => $ua])->get($url);

                return $resp->ok() ? $resp->body() : null;
            } catch (\Throwable $e) {
                return null;
            }
        });
    }

    /**
     * Fill a URL template's {query} placeholder with a url-encoded search term.
     */
    protected function buildUrl(string $template, string $query): string
    {
        return str_replace('{query}', rawurlencode($query), $template);
    }
}
