<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\BinanceService;

class MarketPriceController extends Controller
{
    protected $binanceService;

    public function __construct(BinanceService $binanceService)
    {
        $this->binanceService = $binanceService;
    }

    /**
     * Get top markets with real-time prices
     */
    public function topMarkets(Request $request)
    {
        try {
            // Popular trading pairs - Top 12 coins from Binance for best user experience
            // Removed MATIC as it's not available on Binance main trading
            // Added AVAX, TRX, LINK for better diversity (12 coins total)
            $symbols = [
                'BTCUSDT',  // Bitcoin
                'ETHUSDT',  // Ethereum
                'BNBUSDT',  // Binance Coin
                'SOLUSDT',  // Solana
                'XRPUSDT',  // Ripple
                'ADAUSDT',  // Cardano
                'DOGEUSDT', // Dogecoin
                'DOTUSDT',  // Polkadot
                'LTCUSDT',  // Litecoin
                'AVAXUSDT', // Avalanche
                'TRXUSDT',  // Tron
                'LINKUSDT', // Chainlink
            ];
            
            $tickers = $this->binanceService->getMultipleTickers($symbols);
            
            $markets = [];
            foreach ($symbols as $symbol) {
                if (isset($tickers[$symbol]) && $tickers[$symbol] !== null) {
                    $ticker = $tickers[$symbol];
                    $pair = str_replace('USDT', '/USDT', $symbol);
                    $coin = str_replace('USDT', '', $symbol);
                    
                    $markets[] = [
                        'symbol' => $symbol,
                        'pair' => $pair,
                        'coin' => $coin,
                        'price' => (float) $ticker['price'],
                        'priceChange' => (float) $ticker['priceChange'],
                        'priceChangePercent' => (float) $ticker['priceChangePercent'],
                        'highPrice' => (float) $ticker['highPrice'],
                        'lowPrice' => (float) $ticker['lowPrice'],
                        'volume' => (float) $ticker['volume'],
                        'quoteVolume' => (float) $ticker['quoteVolume'],
                    ];
                }
            }

            // If no real data available, return empty array (frontend WebSocket will provide data)
            // DO NOT return mock data - let frontend WebSocket handle it
            return response()->json([
                'success' => true,
                'markets' => $markets,
                'message' => count($markets) === 0 ? 'Real-time data will be provided by WebSocket' : null
            ]);
        } catch (\Exception $e) {
            \Log::error('MarketPriceController Error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to load market data',
                'markets' => []
            ], 500);
        }
    }

    /**
     * Get price for a specific coin
     */
    public function getCoinPrice(Request $request, $coin)
    {
        $price = $this->binanceService->getCoinPrice($coin);
        
        if ($price === null) {
            return response()->json([
                'success' => false,
                'message' => 'Price not found for ' . $coin
            ], 404);
        }

        return response()->json([
            'success' => true,
            'coin' => strtoupper($coin),
            'price' => $price
        ]);
    }

    /**
     * Fallback USD prices when Binance API is unreachable (e.g. production firewall/region block).
     * Used only for getCoinPrices so Assets balance list always shows a value.
     */
    private static function getFallbackPriceForCoin(string $coin): ?float
    {
        $fallbacks = [
            'BTC' => 95000.0,
            'ETH' => 3500.0,
            'BNB' => 600.0,
            'SOL' => 220.0,
            'XRP' => 2.0,
            'ADA' => 0.9,
            'DOGE' => 0.4,
            'DOT' => 7.0,
            'LTC' => 100.0,
            'AVAX' => 35.0,
            'TRX' => 0.25,
            'LINK' => 18.0,
            'BCH' => 450.0,
            'XLM' => 0.4,
            'UNI' => 10.0,
            'ATOM' => 8.0,
        ];
        return $fallbacks[$coin] ?? null;
    }

    /**
     * Get prices for multiple coins
     * When Binance API is unreachable (e.g. in production), uses fallback prices so Assets page still shows values.
     */
    public function getCoinPrices(Request $request)
    {
        $coinsParam = $request->get('coins', '');
        
        if (empty($coinsParam)) {
            return response()->json([
                'success' => false,
                'message' => 'No coins provided'
            ], 400);
        }

        // Handle comma-separated string or array
        $coins = is_array($coinsParam) ? $coinsParam : explode(',', $coinsParam);
        $coins = array_filter(array_map('trim', $coins));

        if (empty($coins)) {
            return response()->json([
                'success' => false,
                'message' => 'No valid coins provided'
            ], 400);
        }

        $prices = [];
        foreach ($coins as $coin) {
            $coinUpper = strtoupper(trim($coin));
            
            // USDT is always $1.00
            if ($coinUpper === 'USDT') {
                $prices[$coinUpper] = 1.0;
                continue;
            }
            
            $price = $this->binanceService->getCoinPrice($coinUpper);
            if ($price === null) {
                // Production: Binance often unreachable (firewall/region). Use fallback so Assets balance list shows value.
                $fallback = self::getFallbackPriceForCoin($coinUpper);
                if ($fallback !== null) {
                    $prices[$coinUpper] = (float) $fallback;
                }
            } else {
                $prices[$coinUpper] = (float) $price;
            }
        }

        return response()->json([
            'success' => true,
            'prices' => $prices
        ]);
    }
}
