<?php

namespace App\Console\Commands;

use App\Models\Investment;
use Illuminate\Console\Command;

class ManageInvestment extends Command {
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:manage-investment';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Checks investment validity, expiration and topup interval and then tops up appropriately.';

    /**
     * Execute the console command.
     */
    public function handle() {
        $investments = Investment::active()->get();

        foreach ($investments as $investment) {
            $plan = $investment->plan;

            $interval = convert_singular($plan->increment_interval);

            if ($investment->expires_at->isFuture()) {
                $intervalMethod = 'add' . $interval;
                $nextReturn = $investment->next_return->copy()->$intervalMethod();

                if (now()->greaterThanOrEqualTo($investment->next_return)) {
                    $user = $investment->user;

                    $coinBalance = $user->balances()->where('coin_id', $investment->coin->id)->first();

                    $return = $plan->increment * $investment->amount;

                    $coinBalance->increment('value', $return);

                    $investment->update([
                        'next_return' => $nextReturn,
                    ]);

                    $this->info("Topped up for {$investment->user->pay_id}. Next topup is {$nextReturn}");
                } else {
                    $nextReturn = $investment->next_return->diffForHumans();
                    $this->warn("No topup for {$investment->user->pay_id}. Next topup is {$nextReturn}");
                }
            } else {
                $this->warn("Investment has expired.");
                $investment->update([
                    'is_active' => false,
                ]);
            }
        }
    }
}
