<?php

namespace App\Console\Commands;

use App\Models\CreditTransaction;
use App\Models\User;
use Illuminate\Console\Command;

class ProcessMonthlyCredits extends Command
{
    protected $signature = 'credits:monthly-reset';
    protected $description = 'Bucht Bonus-Verbrauch ab für den Vormonat';

    public function handle(): void
    {
        $lastMonth = now()->subMonth();
        $processed = 0;

        User::whereHas('subscription', fn($q) =>
            $q->whereIn('status', ['active', 'gifted'])
        )->each(function (User $user) use ($lastMonth, &$processed) {

            $planLimit = $user->subscription?->plan?->credit_limit ?? 0;

            // Unlimited → nichts tun
            if ($planLimit === 0) return;

            // Verbrauch letzten Monat
            $usage = (int) $user->agentLogs()
                ->whereYear('created_at', $lastMonth->year)
                ->whereMonth('created_at', $lastMonth->month)
                ->sum('credits');

            // Unter Plan-Limit → kein Bonus-Abzug
            if ($usage <= $planLimit) return;

            $overUsage = $usage - $planLimit;

            // Verfügbares Guthaben prüfen
            $bonusLeft = max(0, (int) $user->creditTransactions()->sum('amount'));

            if ($bonusLeft <= 0) return;

            $deduct = min($overUsage, $bonusLeft);

            CreditTransaction::create([
                'user_id'     => $user->id,
                'amount'      => -$deduct,
                'type'        => 'usage',
                'description' => 'Bonus-Verbrauch ' . $lastMonth->translatedFormat('M Y') . ' (' . $overUsage . ' über Plan-Limit)',
            ]);

            $processed++;
            $this->info("-{$deduct} Credits von {$user->name} ({$usage}/{$planLimit}, {$overUsage} über Limit)");
        });

        $this->info("{$processed} Bonus-Abbuchungen verarbeitet.");
    }
}
