<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Services\CoinPriceService;

class UpdateCryptoPrices extends Command
{
    protected $signature = 'crypto:update-prices';
    protected $description = 'Update cryptocurrency prices from CoinEx REST API and Tetherland';

    public function handle()
    {
        $this->info('Starting price update...');
        
        while (true) {
            try {
                $service = new CoinPriceService();
                
                // Force refresh prices
                $prices = $service->refreshPrices();
                
                $count = count($prices);
                $this->info('[' . date('Y-m-d H:i:s') . '] Updated ' . $count . ' cryptocurrency prices');
                
                if ($count === 0) {
                    $this->warn('No prices fetched! Check logs at storage/logs/laravel.log');
                }
                
                // Show some sample prices
                if (isset($prices['BTC'])) {
                    $this->info('  BTC: $' . number_format($prices['BTC']['usdt_price'], 2) . ' = ' . number_format($prices['BTC']['buy']) . ' IRT');
                }
                if (isset($prices['ETH'])) {
                    $this->info('  ETH: $' . number_format($prices['ETH']['usdt_price'], 2) . ' = ' . number_format($prices['ETH']['buy']) . ' IRT');
                }
                if (isset($prices['USDT'])) {
                    $this->info('  USDT: ' . number_format($prices['USDT']['buy']) . ' IRT');
                } else {
                    $this->warn('  USDT price not available');
                }
                
            } catch (\Exception $e) {
                $this->error('Error updating prices: ' . $e->getMessage());
                Log::error('UpdateCryptoPrices: ' . $e->getMessage());
            }
            
            // Update every 5 seconds for near real-time prices
            sleep(5);
        }
        
        return 0;
    }
}
