<?php

namespace App\Services;

use App\Events\TradeExecuted;
use App\Models\Trade;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\Facades\Log;

class WebSocketBroadcastingService
{
    /**
     * Broadcast a trade execution to connected clients
     */
    public function broadcastTrade(Trade $trade): void
    {
        try {
            // Dispatch the trade executed event
            broadcast(new TradeExecuted($trade));
            
            // Log the broadcast
            Log::info('Trade broadcasted', [
                'trade_id' => $trade->id,
                'market_id' => $trade->market_id,
                'price' => $trade->price,
                'quantity' => $trade->quantity,
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to broadcast trade: ' . $e->getMessage(), [
                'trade_id' => $trade->id,
                'market_id' => $trade->market_id,
            ]);
        }
    }

    /**
     * Broadcast order book updates
     */
    public function broadcastOrderBookUpdate(string $marketId, array $data): void
    {
        try {
            // Broadcast to market-specific channel
            Broadcast::channel('market.' . $marketId)->push('orderbook.update', $data);
            
            // Log the broadcast
            Log::info('Order book update broadcasted', [
                'market_id' => $marketId,
                'data' => $data,
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to broadcast order book update: ' . $e->getMessage(), [
                'market_id' => $marketId,
            ]);
        }
    }

    /**
     * Broadcast market price updates
     */
    public function broadcastPriceUpdate(string $marketId, float $price, float $volume): void
    {
        try {
            // Broadcast to market-specific channel
            Broadcast::channel('market.' . $marketId)->push('price.update', [
                'price' => $price,
                'volume' => $volume,
                'timestamp' => now()->toISOString(),
            ]);
            
            // Broadcast to general market updates
            Broadcast::channel('market.updates')->push('price.change', [
                'market_id' => $marketId,
                'price' => $price,
                'volume' => $volume,
                'timestamp' => now()->toISOString(),
            ]);
            
            // Log the broadcast
            Log::info('Price update broadcasted', [
                'market_id' => $marketId,
                'price' => $price,
                'volume' => $volume,
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to broadcast price update: ' . $e->getMessage(), [
                'market_id' => $marketId,
                'price' => $price,
            ]);
        }
    }
}