<?php

namespace App\Jobs;

use App\Models\LiveTrade;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public function handle()
    {
        Log::info("🚀 Running UpdateLiveTradesJob...");

        // Fetch only open trades
        $trades = LiveTrade::where('status', 'open')->get();
        Log::info("Found {$trades->count()} open trades.");

        foreach ($trades as $trade) {
            try {
                $symbol = strtoupper($trade->symbol);
                $currentPrice = $this->fetchCurrentPrice($symbol, $trade->market_type);

                if (!$currentPrice || !is_numeric($currentPrice)) {
                    Log::warning("⚠️ Skipping trade {$trade->id} — invalid price for {$symbol}");
                    continue;
                }

                // ✅ Recalculate trade metrics
                $currentValue = $trade->units * $currentPrice * $trade->leverage;
                $profitLoss = $trade->side === 'buy'
                    ? ($currentPrice - $trade->entry_price) * $trade->units * $trade->leverage
                    : ($trade->entry_price - $currentPrice) * $trade->units * $trade->leverage;

                // ✅ Update trade record
                $trade->update([
                    'current_price' => $currentPrice,
                    'current_value' => $currentValue,
                    'profit_loss' => $profitLoss,
                ]);

                // 🕒 Auto-close expired trades
                if ($trade->expires_at && now()->greaterThan($trade->expires_at)) {
                    $this->closeTrade($trade);
                }
            } catch (\Exception $e) {
                Log::error("❌ Failed to update trade {$trade->id}: " . $e->getMessage());
            }
        }
    }

    private function fetchCurrentPrice($symbol, $marketType)
    {
        // ✅ Binance for crypto
        if ($marketType === 'crypto' || str_ends_with($symbol, 'USDT')) {
            $data = Http::get("https://api.binance.com/api/v3/ticker/price", [
                'symbol' => $symbol,
            ])->json();

            if (isset($data['code'])) {
                Log::warning("❌ Binance error for {$symbol}: " . json_encode($data));
                return null;
            }

            return (float) $data['price'];
        }

        // ✅ TwelveData for stocks/forex
        $response = Http::get("https://api.twelvedata.com/quote", [
            'symbol' => $symbol,
            'apikey' => config('services.twelvedata.key'),
        ])->json();

        if (isset($response['close'])) {
            return (float) $response['close'];
        }

        Log::warning("❌ TwelveData error for {$symbol}: " . json_encode($response));
        return null;
    }

    private function closeTrade($trade)
    {
        $user = $trade->user;
        $finalProfit = $trade->profit_loss;

        // 💰 Return amount + profit/loss to user balance
        $user->balance += ($trade->amount + $finalProfit);
        $user->save();

        // 🏁 Mark trade as closed
        $trade->update([
            'status' => 'closed',
            'closed_price' => $trade->current_price,
            'closed_at' => now(),
        ]);

        Log::info("✅ Trade {$trade->id} auto-closed. Profit: {$finalProfit}");
    }
}
