<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Link;
use App\Jobs\SendLinkNotifications;
use App\Enums\LinkStatus;

class RetryNotifications extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'notifications:retry';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Ré-envoie les notifications (email/WhatsApp) pour les liens en échec';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $links = Link::where('status', LinkStatus::Failed)
                     ->where('no_relance', false)
                     ->get();

        if ($links->isEmpty()) {
            $this->info('Aucun lien en échec à relancer (liens ignorés s\'ils sont en opt-out).');
            return 0;
        }

        foreach ($links as $link) {
            SendLinkNotifications::dispatch($link);
            $link->update(['status' => 'pending']);

            $this->info("Relance en file pour le lien ID {$link->id}");
        }

        return 0;
    }
}