<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;
use Tests\TestCase;
use App\Models\Campaign;
use App\Models\Donateur;
use App\Models\Link;
use Illuminate\Support\Str;
use App\Enums\LinkStatus;
use App\Jobs\SendLinkNotifications;

class RetryNotificationsTest extends TestCase
{
    use RefreshDatabase;

    public function test_opted_out_links_are_not_requeued()
    {
        Bus::fake();

        $campaign = Campaign::create([
            'name'    => 'Test',
            'slug'    => 'test',
            'message' => 'msg',
        ]);

        $donateur = Donateur::create([
            'nom'    => 'Doe',
            'prenom' => 'John',
        ]);

        $linkOptOut = Link::create([
            'campaign_id' => $campaign->id,
            'donateur_id' => $donateur->id,
            'token'       => Str::random(40),
            'status'      => LinkStatus::Failed,
            'no_relance'  => true,
        ]);

        $linkQueued = Link::create([
            'campaign_id' => $campaign->id,
            'donateur_id' => $donateur->id,
            'token'       => Str::random(40),
            'status'      => LinkStatus::Failed,
        ]);

        $this->artisan('notifications:retry')
             ->assertExitCode(0);

        $linkOptOut->refresh();
        $linkQueued->refresh();

        $this->assertEquals(LinkStatus::Failed, $linkOptOut->status);
        $this->assertEquals(LinkStatus::Pending, $linkQueued->status);

        Bus::assertDispatched(SendLinkNotifications::class, function ($job) use ($linkQueued) {
            return $job->link->is($linkQueued);
        });

        Bus::assertNotDispatched(SendLinkNotifications::class, function ($job) use ($linkOptOut) {
            return $job->link->is($linkOptOut);
        });
    }
}
