<?php

namespace App\Console\Commands;

use App\Models\Boost;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class DailyBoostDeduction extends Command
{
    protected $signature   = 'boosts:deduct-daily';
    protected $description = 'Deduct daily bid amount from wallets for all active boosts';

    public function handle(): void
    {
        $processed = 0;
        $paused    = 0;

        Boost::with(['user.wallet', 'listing'])
            ->where('status', 'active')
            ->chunk(100, function ($boosts) use (&$processed, &$paused) {
                foreach ($boosts as $boost) {
                    $wallet = $boost->user?->wallet;

                    if (!$wallet) {
                        $boost->update(['status' => 'paused']);
                        $paused++;
                        continue;
                    }

                    $success = $wallet->debit(
                        $boost->bid_amount,
                        "Daily boost fee — {$boost->listing?->title} in {$boost->city}"
                    );

                    if ($success) {
                        $boost->update(['last_deducted_at' => now()]);
                        $processed++;
                    } else {
                        // Insufficient balance — pause the boost
                        $boost->update(['status' => 'exhausted']);
                        $paused++;

                        Log::info("Boost #{$boost->id} paused (listing: {$boost->listing_id}, user: {$boost->user_id}) - insufficient balance.");
                    }
                }
            });

        $this->info("✓ Processed: {$processed} boosts deducted, {$paused} paused (insufficient balance).");
        Log::info("DailyBoostDeduction: {$processed} deducted, {$paused} paused.");
    }
}
