<?php

namespace App\Console\Commands;

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

use function Laravel\Prompts\info;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update the order book in Redis for a specific market';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $marketId = $this->option('market');
        
        if (!$marketId) {
            $this->error('Please specify a market ID using --market=ID');
            return 1;
        }
        
        $this->info("Loading order book for market: {$marketId}");
        
        try {
            $redis = Redis::connection();
            
            // Clear existing order book data for this market
            $redis->del("orderbook:{$marketId}:buy");
            $redis->del("orderbook:{$marketId}:sell");
            
            // Load all active orders for the market
            $openOrders = Order::forMarket($marketId)->active()->get();
            
            foreach ($openOrders as $order) {
                // Add order to the appropriate Redis sorted set
                $price = $order->price;
                $orderId = $order->id;
                $side = $order->side;
                
                // Add to sorted set based on price and side
                $redis->zadd("orderbook:{$marketId}:{$side}", $price, $orderId);
            }
            
            $this->info("Order book updated for market: {$marketId} (" . count($openOrders) . " orders)");
        } catch (\Exception $e) {
            Log::error('Order book worker error: ' . $e->getMessage());
            $this->error('Error: ' . $e->getMessage());
            return 1;
        }
        
        return 0;
    }
}
