<?php

namespace Tests\Unit\Models;

use App\Events\NewArticleFetched;
use App\Models\Article;
use App\Models\Feed;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class ArticleTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        Http::fake([
            '*' => Http::response('', 500),
        ]);
    }

    public function test_feed_relationship(): void
    {
        $feed = Feed::factory()->create();
        $article = Article::factory()->create(['feed_id' => $feed->id]);

        $this->assertInstanceOf(Feed::class, $article->feed);
        $this->assertEquals($feed->id, $article->feed->id);
    }

    public function test_route_articles_relationship(): void
    {
        $feed = Feed::factory()->create();
        $article = Article::factory()->create(['feed_id' => $feed->id]);

        $this->assertCount(0, $article->routeArticles);
    }

    public function test_dispatch_fetched_event_fires_new_article_fetched_event(): void
    {
        Event::fake([NewArticleFetched::class]);

        $feed = Feed::factory()->create();
        $article = Article::factory()->create(['feed_id' => $feed->id]);

        $article->dispatchFetchedEvent();

        Event::assertDispatched(NewArticleFetched::class, function ($event) use ($article) {
            return $event->article->id === $article->id;
        });
    }

    public function test_is_published_attribute(): void
    {
        $feed = Feed::factory()->create();
        $article = Article::factory()->create(['feed_id' => $feed->id]);

        $this->assertFalse($article->is_published);
    }

    public function test_validated_at_is_cast_to_datetime(): void
    {
        $feed = Feed::factory()->create();
        $article = Article::factory()->create([
            'feed_id' => $feed->id,
            'validated_at' => now(),
        ]);

        $this->assertInstanceOf(Carbon::class, $article->validated_at);
    }
}
