<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\AiTradeBot;
use App\Services\OrderService;

class NormalizeClosedBotOrders extends Command
{
    protected $signature = 'orders:normalize-closed-bots';

    protected $description = 'Normalize order profit_loss for already-closed bots so Order Record sum matches Total Profit/Loss (admin set %)';

    public function handle(OrderService $orderService): int
    {
        $bots = AiTradeBot::where('status', 'closed')
            ->whereNotNull('admin_activated_at')
            ->whereNotNull('admin_set_trading_time_minutes')
            ->get();

        $count = 0;
        foreach ($bots as $bot) {
            $amount = (float) $bot->amount;
            $maxProfitPercent = (float) ($bot->max_profit_percent ?? 0);
            $maxLossPercent = (float) ($bot->max_loss_percent ?? 0);
            $netPercent = $maxProfitPercent - $maxLossPercent;
            $finalNetPL = ($netPercent / 100) * $amount;

            $orderService->normalizeOrdersToMatchFinalPL($bot, $finalNetPL);
            $count++;
        }

        $this->info("Normalized orders for {$count} closed bot(s).");
        return Command::SUCCESS;
    }
}
