<?php

namespace App\Console\Commands;

use App\Jobs\SyncJobSource;
use App\Models\JobSource;
use App\Services\Settings\SettingsService;
use Illuminate\Console\Command;

class SyncActiveJobSources extends Command
{
    protected $signature = 'jobs:sync-sources {--source= : Sync one active source by slug}';

    protected $description = 'Dispatch queued sync jobs for active remote job sources.';

    public function handle(SettingsService $settings): int
    {
        if (! $settings->isEnabled('job_sources.enabled')) {
            $this->warn('Job source syncing is disabled in platform settings.');

            return self::SUCCESS;
        }

        $query = JobSource::query()
            ->where('is_active', true)
            ->orderBy('name');

        if (filled($this->option('source'))) {
            $query->where('slug', (string) $this->option('source'));
        }

        $sources = $query->get();

        if ($sources->isEmpty()) {
            $this->warn('No active job sources matched.');

            return self::SUCCESS;
        }

        $sources->each(fn (JobSource $source) => SyncJobSource::dispatch($source));

        $this->info("Queued {$sources->count()} job source sync task(s).");

        return self::SUCCESS;
    }
}
