<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use App\Models\UserBalance;
use App\Models\AiTradeBot;
use Illuminate\Support\Facades\DB;

class FixUserBalanceQuota extends Command
{
    protected $signature = 'user:fix-balance-quota {user_id?}';
    protected $description = 'Fix user balance and quota issues (negative locked balance, quota exceeding authorization)';

    public function handle()
    {
        $userId = $this->argument('user_id');
        
        if ($userId) {
            $users = collect([User::find($userId)]);
        } else {
            $users = User::all();
        }
        
        $users = $users->filter();
        
        if ($users->isEmpty()) {
            $this->error('No users found!');
            return 1;
        }
        
        $this->info("Fixing balance and quota for " . $users->count() . " user(s)...\n");
        
        foreach ($users as $user) {
            $this->fixUser($user);
        }
        
        $this->info("\n✅ All fixes completed!");
        return 0;
    }
    
    protected function fixUser(User $user)
    {
        $this->line("User ID: {$user->id}");
        
        // Get current values
        $authorizationQuota = (float) $user->authorization_quota;
        $currentAvailableQuota = (float) $user->available_quota;
        $currentLockedBalance = (float) $user->locked_balance;
        
        // Get USDT balance
        $usdtBalance = UserBalance::where('user_id', $user->id)
            ->where('coin_name', 'USDT')
            ->first();
        
        // Calculate correct values
        $correctAvailableQuota = min($currentAvailableQuota, $authorizationQuota);
        
        // Calculate expected locked balance from active bots
        $activeBots = AiTradeBot::where('user_id', $user->id)
            ->whereIn('status', ['active', 'paused'])
            ->get();
        
        $expectedLockedBalance = max(0, $activeBots->sum('amount'));
        
        $hasChanges = false;
        
        // Fix available quota
        if ($currentAvailableQuota != $correctAvailableQuota) {
            $this->line("  Available Quota: {$currentAvailableQuota} → {$correctAvailableQuota}");
            $hasChanges = true;
        }
        
        // Fix locked balance
        if ($currentLockedBalance != $expectedLockedBalance) {
            $this->line("  Locked Balance: {$currentLockedBalance} → {$expectedLockedBalance}");
            $hasChanges = true;
        }
        
        if (!$hasChanges) {
            $this->line("  ✓ No fixes needed");
            return;
        }
        
        // Apply fixes
        DB::transaction(function () use ($user, $correctAvailableQuota, $expectedLockedBalance, $usdtBalance) {
            $user->update([
                'available_quota' => $correctAvailableQuota,
                'locked_balance' => $expectedLockedBalance,
            ]);
            
            if ($usdtBalance) {
                $usdtBalance->update(['locked_balance' => $expectedLockedBalance]);
            }
        });
        
        $this->info("  ✓ Fixed!");
    }
}
