<?php

namespace App\Console\Commands;

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

class ProcessInvestmentRoi extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'plans:process-roi {--investment-id= : Process specific investment ID}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Process ROI for active investment plans';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Starting investment ROI processing...');

        try {
            $investmentId = $this->option('investment-id');

            if ($investmentId) {
                // Process specific investment
                $investment = Investment::find($investmentId);
                if (!$investment) {
                    $this->error("Investment with ID {$investmentId} not found.");
                    return Command::FAILURE;
                }

                $this->info("Processing investment ID: {$investmentId}");
                ProcessPlanInvestmentReturns::dispatchSync($investment);
            } else {
                // Process all investments
                $this->info('Processing all active investments...');
                ProcessPlanInvestmentReturns::dispatchSync();
            }

            $this->info('Investment ROI processing job dispatched successfully!');
            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('Error processing investment ROI: ' . $e->getMessage());
            return Command::FAILURE;
        }
    }
}
