<?php

namespace App\Console\Commands;

use App\Models\Market;
use App\Models\Order;
use App\Services\OrderMatchingService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

use function Laravel\Prompts\info;

class MarketMatchingWorker extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'trading:market-matcher {--market= : The market ID to process}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run the market matching engine for a specific market';

    /**
     * Execute the console command.
     */
    public function handle(OrderMatchingService $matchingService)
    {
        $marketId = $this->option('market');
        
        if (!$marketId) {
            $this->error('Please specify a market ID using --market=ID');
            return 1;
        }
        
        $this->info("Starting market matching worker for market: {$marketId}");
        
        try {
            // Load open orders for this market from Redis sorted sets
            $redis = Redis::connection();
            
            // Get open orders for the market
            $openOrders = Order::forMarket($marketId)->active()->orderBy('created_at')->get();
            
            foreach ($openOrders as $order) {
                // Process the order through the matching engine
                if ($order->type === 'market') {
                    $matchingService->processMarketOrder($order);
                } else {
                    $matchingService->processOrder($order);
                }
                
                // Small delay to prevent overwhelming the system
                usleep(10000); // 10ms delay
            }
            
            $this->info("Market matching completed for market: {$marketId}");
        } catch (\Exception $e) {
            Log::error('Market matching worker error: ' . $e->getMessage());
            $this->error('Error: ' . $e->getMessage());
            return 1;
        }
        
        return 0;
    }
}
