<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\UserCoinBalance;
use App\Models\Coin;

class AdjustUserBalances extends Command
{
    protected $signature = 'adjust:user-balances';
    protected $description = 'Adjust user balances based on updated coin prices';

    public function handle()
    {
        $coins = Coin::all(); // Fetch all coins

        foreach ($coins as $coin) {
            $userBalances = UserCoinBalance::where('coin_id', $coin->id)->get(); // Get all balances for the coin
            $oldPrice = $coin->getOriginal('latest_price'); // Get the old price before the update
            $newPrice = $coin->latest_price; // Get the new updated price

            if ($oldPrice > 0 && $newPrice > 0) {
                // Calculate the percentage change
                $percentageChange = (($newPrice - $oldPrice) / $oldPrice) * 100;
                $this->info("Processing {$coin->name}: Old Price = $oldPrice, New Price = $newPrice, Change = {$percentageChange}%");

                foreach ($userBalances as $userBalance) {
                    $oldCryptoBalance = $userBalance->balance; // User's current crypto balance

                    // Adjust the crypto balance based on the percentage change
                    $adjustedBalance = $oldCryptoBalance * (1 + ($percentageChange / 100));

                    // Debugging log for before and after values
                    $this->info("User ID {$userBalance->user_id}: Old Balance = $oldCryptoBalance, New Balance = $adjustedBalance");

                    // Save the new balance
                    $userBalance->balance = $adjustedBalance;
                    $userBalance->save();
                }
            } else {
                $this->warn("Skipped {$coin->name}: Invalid Old Price = $oldPrice or New Price = $newPrice");
            }
        }

        $this->info('User balances adjusted successfully based on price changes!');
    }
}
