<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Order;
use Illuminate\Support\Facades\Log;

class CheckMarginLiquidation extends Command
{
    protected $signature = 'orders:check-liquidation';
    protected $description = 'Check and liquidate orders that have reached margin call levels';

    public function handle()
    {
        $orders = Order::where('status', 'open')->get();
        $liquidatedCount = 0;

        foreach ($orders as $order) {
            if ($order->shouldLiquidate()) {
                $order->close();
                $liquidatedCount++;
                
                Log::info('Order liquidated due to margin call', [
                    'order_id' => $order->id,
                    'user_id' => $order->user_id,
                    'currency' => $order->currency->name,
                    'margin_level' => $order->user->calculateMarginLevel(),
                    'unrealized_pl' => $order->calculateUnrealizedPL(true)
                ]);
            }
        }

        $this->info("Liquidated {$liquidatedCount} orders due to margin calls");
    }
} 