<?php

namespace Tests\Feature\Http\Console\Commands;

use App\Jobs\ArticleDiscoveryJob;
use App\Models\Feed;
use App\Models\Setting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Illuminate\Testing\PendingCommand;
use Tests\TestCase;

class FetchNewArticlesCommandTest extends TestCase
{
    use RefreshDatabase;

    public function test_command_runs_successfully_when_feeds_exist(): void
    {
        // Arrange
        Feed::factory()->create(['is_active' => true]);

        // Act & Assert
        /** @var PendingCommand $exitCode */
        $exitCode = $this->artisan('article:refresh');
        $exitCode->assertSuccessful();

        // The command should complete without the "no feeds" message
        $exitCode->assertExitCode(0);
    }

    public function test_command_does_not_dispatch_jobs_when_no_active_feeds_exist(): void
    {
        // Arrange
        Queue::fake();
        // No active feeds created

        // Act
        /** @var PendingCommand $exitCode */
        $exitCode = $this->artisan('article:refresh');

        // Assert
        $exitCode->assertSuccessful();
        Queue::assertNotPushed(ArticleDiscoveryJob::class);
    }

    public function test_command_does_not_dispatch_jobs_when_only_inactive_feeds_exist(): void
    {
        // Arrange
        Queue::fake();
        Feed::factory()->create(['is_active' => false]);

        // Act
        /** @var PendingCommand $exitCode */
        $exitCode = $this->artisan('article:refresh');

        // Assert
        $exitCode->assertSuccessful();
        Queue::assertNotPushed(ArticleDiscoveryJob::class);
    }

    public function test_command_logs_when_no_feeds_available(): void
    {
        // Arrange
        Queue::fake();

        // Act
        /** @var PendingCommand $exitCode */
        $exitCode = $this->artisan('article:refresh');

        // Assert
        $exitCode->assertSuccessful();
        $exitCode->expectsOutput('No active feeds found. Article discovery skipped.');
    }

    public function test_command_skips_when_article_processing_disabled(): void
    {
        // Arrange
        Queue::fake();
        Setting::create([
            'key' => 'article_processing_enabled',
            'value' => '0',
        ]);

        // Act
        /** @var PendingCommand $exitCode */
        $exitCode = $this->artisan('article:refresh');

        // Assert
        $exitCode->assertSuccessful();
        $exitCode->expectsOutput('Article processing is disabled. Article discovery skipped.');
        Queue::assertNotPushed(ArticleDiscoveryJob::class);
    }
}
