<?php

namespace App\Console\Commands;

use App\Models\BotRuntimeState;
use App\Services\FlatTrade\FlatTradeWebSocketService;
use App\Services\MarketData\MarketDataSyncService;
use Illuminate\Console\Command;

class FlatTradeWebSocketCommand extends Command
{
    protected $signature = 'flattrade:websocket';

    protected $description = 'Poll live FlatTrade quotes using admin credentials (market feed)';

    public function handle(FlatTradeWebSocketService $websocket, MarketDataSyncService $marketSync): int
    {
        if (config('flattrade.mock')) {
            $this->error('FLATTRADE_MOCK is enabled. Set FLATTRADE_MOCK=false for real data.');

            return self::FAILURE;
        }

        $account = $websocket->marketFeedAccount();
        if (! $account) {
            $this->error('Admin FlatTrade market feed is not connected.');

            return self::FAILURE;
        }

        $this->info("Live feed worker using admin account: {$account->client_id}");

        while (true) {
            try {
                $instruments = $marketSync->syncScanUniverse();
                BotRuntimeState::heartbeat('websocket', 'running', [
                    'feed_client' => $account->client_id,
                    'instruments' => $instruments->count(),
                ]);
            } catch (\Throwable $e) {
                $this->error($e->getMessage());
                BotRuntimeState::heartbeat('websocket', 'failed', ['error' => $e->getMessage()]);
            }

            sleep(5);
        }
    }
}
