<?php

namespace App\Console\Commands;

use App\Jobs\ProcessPendingProviderNotifications;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Mtc\MercuryDataModels\PendingProviderNotification;

class DrainPendingProviderNotifications extends Command
{
    protected $signature = 'notifications:drain-pending {--provider= : Limit to a single provider key}';

    protected $description = 'Dispatch the serialized drainer for providers with a pending notification backlog (current tenant).';

    public function handle(): int
    {
        $providers = $this->option('provider')
            ? [$this->option('provider')]
            : array_keys(Config::get('pending-notifications.processors', []));

        foreach ($providers as $provider) {
            $hasBacklog = PendingProviderNotification::query()
                ->where('provider', $provider)
                ->exists();

            if ($hasBacklog) {
                ProcessPendingProviderNotifications::dispatch($provider);
            }
        }

        return self::SUCCESS;
    }
}
