<?php

namespace App\Services;

use App\Models\TradingAccount;

class BrokerConnectionService
{
    public function metaApiTokenConfigured(): bool
    {
        return filled(config('services.metaapi.token'));
    }

    public function forexCalendarKeyConfigured(): bool
    {
        return filled(config('services.forex_calendar.key'));
    }

    public function connectionStatus(TradingAccount $account): array
    {
        if (! $account->api_provider) {
            return [
                'connected' => false,
                'status' => 'manual',
                'message' => 'This account is in manual mode.',
            ];
        }

        if ($account->api_provider === 'metaapi' && ! $this->metaApiTokenConfigured()) {
            return [
                'connected' => false,
                'status' => 'missing_credentials',
                'message' => 'Add METAAPI_TOKEN to .env before connecting this account.',
            ];
        }

        if ($account->api_provider === 'broker_api') {
            return [
                'connected' => false,
                'status' => 'not_implemented',
                'message' => 'Broker API code has not been added yet.',
            ];
        }

        return [
            'connected' => $account->api_connected,
            'status' => $account->api_status,
            'message' => $account->api_connected
                ? 'This account is marked as API connected.'
                : 'API provider is selected, but no live connection has been completed.',
        ];
    }

    public function connect(TradingAccount $account): array
    {
        $status = $this->connectionStatus($account);

        if (! $status['connected']) {
            $account->update([
                'api_connected' => false,
                'api_status' => $status['status'],
                'api_error' => $status['message'],
            ]);
        }

        // Future real API code belongs here.
        // Example for MetaApi later:
        // 1. Send config('services.metaapi.token') to MetaApi SDK/client.
        // 2. Verify $account->api_account_id exists with MetaApi.
        // 3. If the broker confirms access, set api_connected=true and api_status='connected'.

        return $status;
    }
}
