<?php

namespace App\Jobs;

use App\Models\RssFeed;
use App\Services\Admin\RssCrawlerService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class ProcessRssFeed implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 120; // 2 minutes per feed max
    public $tries = 3;     // Retry 3 times if fails

    protected $feed;

    /**
     * Create a new job instance.
     */
    public function __construct(RssFeed $feed)
    {
        $this->feed = $feed;
    }

    /**
     * Execute the job.
     */
    public function handle(RssCrawlerService $crawler)
    {
        Log::info("Queue Processing: {$this->feed->name}");
        $crawler->run($this->feed);
    }

    /**
     * Handle a job failure.
     */
    public function failed(\Throwable $exception)
    {
        Log::error("RSS Job Failed for {$this->feed->name}: " . $exception->getMessage());
    }
}