<?php

namespace App\Console\Commands;

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

class SyncTradingPairs extends Command
{
    protected $signature = 'trading:sync-pairs';
    protected $description = 'Sync trading pairs from CoinEx';

    protected $coinex;

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

    public function handle()
    {
        $this->info('Syncing trading pairs from CoinEx...');

        try {
            $markets = $this->coinex->getMarkets();

            if (empty($markets)) {
                $this->error('No markets returned from CoinEx');
                return;
            }

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

            $synced = 0;
            foreach ($markets as $market) {
                $marketName = $market['market'] ?? null;
                
                if (!$marketName) {
                    continue;
                }

                // Only sync USDT pairs
                if (!str_ends_with($marketName, 'USDT')) {
                    continue;
                }

                $baseCurrency = str_replace('USDT', '', $marketName);

                $tradingPair = TradingPair::updateOrCreate(
                    ['market' => $marketName],
                    [
                        'base_currency' => $baseCurrency,
                        'quote_currency' => 'USDT',
                        'is_active' => true,
                        'min_amount' => $market['min_amount'] ?? 0,
                        'min_total' => $market['min_value'] ?? 0,
                        'maker_fee' => 0.002, // 0.2%
                        'taker_fee' => 0.002, // 0.2%
                        'price_precision' => $market['pricing_decimal'] ?? 8,
                        'amount_precision' => $market['trading_decimal'] ?? 8,
                    ]
                );

                $synced++;
                $this->line("✓ Synced: $marketName");
            }

            $this->info("Successfully synced $synced trading pairs");

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