<?php

namespace App\Console\Commands;

use App\Enums\ProofStatus;
use App\Models\SubscriptionPayment;
use App\Services\Notifier;
use Illuminate\Console\Command;

/**
 * Nag about a stale queue.
 *
 * The threshold is deliberately generous — an hour-old payment is normal
 * business, a four-hour-old one is a shop sitting idle with money already
 * sent. Only the latter is worth interrupting somebody for.
 */
class QueueReminder extends Command
{
    protected $signature = 'central:queue-reminder {--hours=4 : How long a payment may wait before we escalate}';

    protected $description = 'Alert the team when a payment has been waiting too long';

    public function handle(Notifier $notifier): int
    {
        $threshold = now()->copy()->subHours(max(1, (int) $this->option('hours')));

        $stale = SubscriptionPayment::query()
            ->where('status', ProofStatus::Pending)
            ->where('created_at', '<=', $threshold)
            ->count();

        if ($stale === 0) {
            $this->info('Nothing has been waiting too long.');

            return self::SUCCESS;
        }

        $oldest = SubscriptionPayment::query()
            ->where('status', ProofStatus::Pending)
            ->oldest('created_at')
            ->first();

        $waited = (int) $oldest->created_at->diffInHours(now());

        $notifier->sendToRoles(
            ['super_admin', 'admin', 'accountant'],
            'queue.stale',
            'Payments are waiting',
            "{$stale} payment(s) have been unverified for over {$this->option('hours')} hours. "
                ."The oldest ({$oldest->reference}) has waited {$waited} hour(s) — that shop cannot trade.",
            route('payments.queue'),
            ['level' => 'danger'],
        );

        $this->warn("Escalated {$stale} stale payment(s).");

        return self::SUCCESS;
    }
}
