<?php

namespace App\Services\FlatTrade;

use App\Models\BrokerAccount;
use App\Models\User;

class BrokerAccountResolver
{
    public function __construct(private FlatTradeAuthService $auth) {}

    public function marketFeedAccount(): ?BrokerAccount
    {
        $account = BrokerAccount::query()
            ->where('is_market_feed_provider', true)
            ->where('is_connected', true)
            ->first();

        if ($account && $this->auth->isTokenValid($account) && $this->hasCredentials($account)) {
            return $account;
        }

        $admin = User::where('role', 'admin')->with('brokerAccount')->first();
        $adminAccount = $admin?->brokerAccount;

        if ($adminAccount && $this->auth->isTokenValid($adminAccount) && $this->hasCredentials($adminAccount)) {
            return $adminAccount;
        }

        return null;
    }

    public function tradingAccount(User $user): ?BrokerAccount
    {
        $account = $user->brokerAccount;

        if (! $account || ! $this->hasCredentials($account)) {
            return null;
        }

        return $account;
    }

    public function hasCredentials(BrokerAccount $account): bool
    {
        return filled($account->api_key) && filled($account->api_secret);
    }

    public function bindMarketFeedClient(FlatTradeClient $client): ?FlatTradeClient
    {
        $account = $this->marketFeedAccount();
        if (! $account) {
            return null;
        }

        return $this->auth->bindClient($client, $account);
    }

    public function bindTradingClient(FlatTradeClient $client, User $user): ?FlatTradeClient
    {
        $account = $this->tradingAccount($user);
        if (! $account || ! $this->auth->isTokenValid($account)) {
            return null;
        }

        return $this->auth->bindClient($client, $account);
    }

    public function markAsMarketFeedProvider(BrokerAccount $account, User $user): void
    {
        BrokerAccount::query()->update(['is_market_feed_provider' => false]);

        $account->update([
            'is_market_feed_provider' => $user->isAdmin(),
        ]);
    }
}
