<?php

namespace Tests\Unit\Actions;

use App\Actions\FetchWebsiteArticlesAction;
use App\Actions\SaveArticleAction;
use App\Models\Article;
use App\Models\Feed;
use App\Services\Log\LogSaver;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class FetchWebsiteArticlesActionTest extends TestCase
{
    use RefreshDatabase;

    private function action(): FetchWebsiteArticlesAction
    {
        $logSaver = app(LogSaver::class);

        return new FetchWebsiteArticlesAction($logSaver, new SaveArticleAction($logSaver));
    }

    public function test_it_returns_empty_when_no_parser_matches_the_feed(): void
    {
        Http::fake(['*' => Http::response('<html></html>', 200)]);

        $feed = Feed::factory()->create([
            'type' => 'website',
            'url' => 'https://no-parser-for-this-domain.example/',
        ]);

        $this->assertEmpty($this->action()->execute($feed));
        $this->assertSame(0, Article::count());
    }

    public function test_it_returns_empty_when_the_fetch_throws(): void
    {
        Http::fake(fn () => throw new \RuntimeException('connection refused'));

        $feed = Feed::factory()->create([
            'type' => 'website',
            'url' => 'https://www.vrt.be/vrtnws/nl/',
        ]);

        $this->assertEmpty($this->action()->execute($feed));
    }

    public function test_it_returns_a_collection_for_a_feed_with_a_parser(): void
    {
        Http::fake([
            'https://www.vrt.be/vrtnws/nl/' => Http::response('<html><body>Sample VRT content</body></html>', 200),
        ]);

        $feed = Feed::factory()->create([
            'type' => 'website',
            'url' => 'https://www.vrt.be/vrtnws/nl/',
        ]);

        $this->assertInstanceOf(Collection::class, $this->action()->execute($feed));
    }
}
