<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Redis;
use App\Models\Order;

class UpdateOrderBookJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected Order $order;
    protected string $action; // 'add' or 'remove'

    /**
     * Create a new job instance.
     */
    public function __construct(Order $order, string $action = 'add')
    {
        $this->order = $order;
        $this->action = $action;
        $this->onQueue('order_book_updates'); // Queue for order book updates
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $redis = Redis::connection();
        $marketId = $this->order->market_id;
        
        if ($this->action === 'add') {
            // Add order to Redis sorted set for the appropriate side
            $side = $this->order->side;
            $price = $this->order->price;
            $orderId = $this->order->id;
            
            // Add to sorted set based on price
            $redis->zadd("orderbook:{$marketId}:{$side}", $price, $orderId);
        } elseif ($this->action === 'remove') {
            // Remove order from Redis sorted set
            $side = $this->order->side;
            $orderId = $this->order->id;
            
            $redis->zrem("orderbook:{$marketId}:{$side}", $orderId);
        }
    }
}
