<?php

namespace App\Console\Commands;

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

/**
 * The morning summary.
 *
 * One notification, not five: a digest that gets read beats four alerts that
 * get dismissed.
 */
class DailyDigest extends Command
{
    protected $signature = 'central:daily-digest';

    protected $description = 'Send the team a summary of the queue, renewals and new signups';

    public function handle(Notifier $notifier): int
    {
        $pending = SubscriptionPayment::where('status', ProofStatus::Pending)->count();
        $pendingAmount = (float) SubscriptionPayment::where('status', ProofStatus::Pending)->sum('amount');

        $expiring = Subscription::query()
            ->whereIn('status', [SubscriptionStatus::Active->value, SubscriptionStatus::Trial->value])
            ->whereNotNull('ends_at')
            ->whereBetween('ends_at', [now(), now()->copy()->addDays(7)])
            ->count();

        $newTenants = Tenant::where('created_at', '>=', now()->copy()->subDay())->count();

        $lines = array_filter([
            $pending > 0
                ? "{$pending} payment(s) awaiting verification (Rs ".number_format($pendingAmount, 2).')'
                : 'Verification queue is clear',
            $expiring > 0 ? "{$expiring} subscription(s) end within 7 days" : null,
            $newTenants > 0 ? "{$newTenants} new shop(s) signed up yesterday" : null,
        ]);

        // Nothing happened and nothing is waiting: say nothing.
        if ($pending === 0 && $expiring === 0 && $newTenants === 0) {
            $this->info('Nothing worth reporting today.');

            return self::SUCCESS;
        }

        $sent = $notifier->sendToRoles(
            ['super_admin', 'admin', 'accountant'],
            'digest.daily',
            'Today at Thinkrax',
            implode(' · ', $lines),
            route('dashboard'),
            ['level' => $pending > 0 ? 'warning' : 'info'],
        );

        $this->info("Digest sent to {$sent} staff member(s).");

        return self::SUCCESS;
    }
}
