<?php

namespace App\Console\Commands\Launchpad;

use App\Models\Currency\Currency;
use App\Models\Language\LanguageTranslation;
use App\Models\Launchpad\Launchpad;
use App\Models\Launchpad\LaunchpadTransaction;
use App\Models\Wallet\Wallet;
use App\Services\Wallet\WalletService;
use Carbon\Carbon;
use Illuminate\Console\Command;

class LaunchpadClaimReleaseCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'launchpad:claim-release {launchpad}';

    /**
     * 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()
    {
        $launchpad = Launchpad::where('id', $this->argument('launchpad'))->first();

        if(!$launchpad) {
            $this->error('Launchpad was not found');
            return;
        }

        $transactions = LaunchpadTransaction::where('launchpad_id', $launchpad->id)->where('is_credited', false)->get();

        $walletService = new WalletService();

        foreach ($transactions as $transaction) {

            $wallet = Wallet::where('currency_id', $launchpad->currency_id)->where('user_id', $transaction->user_id)->lockForUpdate()->first();

            if($wallet) {

                $amount = math_multiply($launchpad->rate, $transaction->amount);

                $walletService->increase($wallet, $amount);

                $transaction->is_credited = true;
                $transaction->update();
            }
        }
    }
}
