<?php

namespace App\Tests\Domain\Scraping\Adapter;

use App\Domain\Scraping\Domain\Contract\Service\ScraperFactoryInterface;
use App\Domain\Scraping\Domain\Contract\Service\ScraperInterface;

class InMemoryScraperFactory implements ScraperFactoryInterface
{
    /** @var array<string, ScraperInterface> */
    private array $scrapers = [];

    public function createScraper(string $source): ScraperInterface
    {
        if (!isset($this->scrapers[$source])) {
            $this->scrapers[$source] = new InMemoryScraperAdapter();
        }

        return $this->scrapers[$source];
    }

    public function getBestScraper(): ScraperInterface
    {
        return $this->createScraper('best');
    }

    public function getFallbackScraper(): ScraperInterface
    {
        return $this->createScraper('fallback');
    }

    public function getScraperWithFallback(string $preferredType): ScraperInterface
    {
        if (isset($this->scrapers[$preferredType])) {
            return $this->scrapers[$preferredType];
        }

        return $this->getFallbackScraper();
    }

    public function getSupportedTypes(): array
    {
        return array_keys($this->scrapers);
    }

    public function isSupported(string $type): bool
    {
        return isset($this->scrapers[$type]);
    }

    public function addScraper(string $source, ScraperInterface $scraper): void
    {
        $this->scrapers[$source] = $scraper;
    }

    public function clear(): void
    {
        $this->scrapers = [];
    }
}
