<?php

namespace App\Console\Commands\Staking;

use App\Models\Staking\StakingUser;
use App\Repositories\Wallet\WalletRepository;
use App\Services\Wallet\WalletService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Setting;

class StakingStatusCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'staking:status';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // Use chunk to optimize query and avoid memory leak
        StakingUser::active()->where('redemption_date', Carbon::now()->format('Y-m-d 00:00:00'))->chunk(100, function($stakes) {
            foreach ($stakes as $stake) {

                $wallet = (new WalletRepository())->getWalletByCurrency($stake->user_id, $stake->currency_id, false);

                if($wallet) {
                    (new WalletService())->increase($wallet, $stake->reward + $stake->amount, 'wallet');
                }

                $stake->status = 'completed';
                $stake->save();
            }
        });
    }
}
