<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\RssFeed;
use App\Models\Setting;
use App\Jobs\ProcessRssFeed;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schema;

class CrawlRssFeeds extends Command
{
    protected $signature = 'rss:crawl {id?} {--force}';
    protected $description = 'Dynamic RSS Crawler with automatic queue processing';

    public function handle()
    {
        if (!Schema::hasTable('settings')) return;

        $feedId = $this->argument('id');
        $force = $this->option('force');

        // 1. Load Settings from DB
        $settings = Setting::where('group', 'scheduler')->pluck('value', 'key');
        $isEnabled = ($settings['rss_schedule_enabled'] ?? 'true') === 'true';
        $frequency = (int) ($settings['rss_schedule_frequency'] ?? 60); 
        $lastRun = (int) ($settings['rss_last_scheduled_run'] ?? 0);

        // 2. Dynamic Frequency Check (Only check if --force is NOT used)
        if (!$feedId && !$force) {
            if (!$isEnabled) {
                $this->info("Crawler is disabled in Admin Panel.");
                return; // Exits safely without running queue or updating timestamp
            }

            $elapsedMinutes = (now()->timestamp - $lastRun) / 60;
            if ($elapsedMinutes < $frequency) {
                $remaining = round($frequency - $elapsedMinutes);
                $this->info("Dynamic Frequency: {$frequency}min. Skipping. Next run in {$remaining} mins.");
                return; // Exits safely without running queue or updating timestamp
            }
        }

        // 3. Dispatch Feeds
        $query = RssFeed::where('is_active', true);
        if ($feedId) $query->where('id', $feedId);
        $feeds = $query->get();

        if ($feeds->isEmpty()) {
            $this->info("No active feeds found.");
            return;
        }

        $this->info("Dispatching " . $feeds->count() . " feeds...");
        foreach ($feeds as $feed) {
            ProcessRssFeed::dispatch($feed);
            $this->info("Queued: {$feed->name}");
        }

        // 4. Update Time (Only update if we actually ran the full crawler)
        if (!$feedId) {
            Setting::updateOrCreate(
                ['key' => 'rss_last_scheduled_run'],
                ['group' => 'scheduler', 'value' => (string) now()->timestamp]
            );
        }

        // 5. Automatically trigger Queue Worker
        $this->info("Starting immediate queue worker...");
        Artisan::call('queue:work', ['--stop-when-empty' => true, '--tries' => 3]);

        $this->info("Crawl and Queue processing complete.");
    }
}