<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use App\Services\CoinExService;
use App\TradingPair;

class PollTradingData extends Command
{
    protected $signature = 'trading:poll';
    protected $description = 'Poll trading data from CoinEx REST API (fallback for WebSocket)';

    protected $coinex;

    public function __construct()
    {
        parent::__construct();
        $this->coinex = new CoinExService();
    }

    public function handle()
    {
        $this->info('Starting CoinEx Trading Data Polling...');

        // Get active trading pairs
        $tradingPairs = TradingPair::where('is_active', true)->get();
        
        if ($tradingPairs->isEmpty()) {
            $this->error('No active trading pairs found.');
            return;
        }

        $this->info('Polling ' . $tradingPairs->count() . ' markets...');

        while (true) {
            foreach ($tradingPairs as $pair) {
                $this->updateMarketData($pair->market);
            }

            // Wait 2 seconds before next poll
            sleep(2);
        }
    }

    protected function updateMarketData($market)
    {
        try {
            // Get ticker
            $ticker = $this->coinex->getTicker($market);
            
            if ($ticker && isset($ticker['last'])) {
                $priceData = [
                    'market' => $market,
                    'last' => $ticker['last'],
                    'open' => $ticker['open'] ?? 0,
                    'high' => $ticker['high'] ?? 0,
                    'low' => $ticker['low'] ?? 0,
                    'volume' => $ticker['vol'] ?? 0,
                    'change' => isset($ticker['open']) && $ticker['open'] > 0 
                        ? (($ticker['last'] - $ticker['open']) / $ticker['open']) * 100 
                        : 0,
                    'updated_at' => time(),
                ];

                Cache::put("ticker:$market", $priceData, 60);
                $this->line("✓ Ticker: $market = {$ticker['last']}");
            }

            // Get order book
            $orderBook = $this->coinex->getOrderBook($market, 20);
            
            if ($orderBook) {
                $orderBookData = [
                    'market' => $market,
                    'asks' => $orderBook['asks'] ?? [],
                    'bids' => $orderBook['bids'] ?? [],
                    'updated_at' => time(),
                ];

                Cache::put("orderbook:$market", $orderBookData, 60);
                $this->line("✓ OrderBook: $market updated");
            }

        } catch (\Exception $e) {
            $this->error("Error updating $market: " . $e->getMessage());
        }
    }
}
