import type { BalancesData, BankAccountsData, SupportBanksData, TotalAssetValue } from "@/api/types";
import { defineStore } from "pinia";
import { client, safeClient } from "@/api";

interface State {
  totalAssetValue: TotalAssetValue;
  balances: BalancesData;
  fundingBalances: BalancesData;
  tradingBalances: BalancesData;
  bankAccounts: BankAccountsData["data"];
  supportBanks: SupportBanksData["data"];
}

export const useWalletStore = defineStore("wallet", () => {
  const state = reactive<State>({
    totalAssetValue: {
      fundingValueUsd: "0",
      tradingValueUsd: "0",
      totalValueUsd: "0",
    },
    balances: [],
    fundingBalances: [],
    tradingBalances: [],
    bankAccounts: [],
    supportBanks: [],
  });

  async function initializeWallet() {
    syncTotalAssetValue();
    syncBalances();
    syncBankAccounts();
    syncSupportBanks();
  }

  async function syncTotalAssetValue() {
    const { data } = await safeClient(() => client.api.wallet.total_value.get(), { silent: true });
    if (data.value)
      state.totalAssetValue = data.value;
  }

  async function syncBalances() {
    const { data: balances } = await safeClient(() => client.api.wallet.balances.get(), { silent: true });
    state.balances = balances.value || [];
  }

  async function syncFundingBalances() {
    const { data: balances } = await safeClient(() => client.api.wallet.balances.get({
      query: { accountType: "funding" },
    }), { silent: true });
    state.fundingBalances = balances.value || [];
  }

  async function syncTradingBalances() {
    const { data: balances } = await safeClient(() => client.api.wallet.balances.get({
      query: { accountType: "trading" },
    }), { silent: true });
    state.tradingBalances = balances.value || [];
  }

  async function syncBankAccounts(data?: BankAccountsData["data"]) {
    if (data) {
      state.bankAccounts = data;
      return;
    }
    const { data: bankAccounts } = await safeClient(() => client.api.bank_account.get(), { silent: true });
    state.bankAccounts = bankAccounts.value?.data || [];
  }

  async function syncSupportBanks() {
    const { data: banks } = await safeClient(() => client.api.bank_account.banks.get(), { silent: true });
    state.supportBanks = banks.value?.data || [];
  }

  return {
    ...toRefs(state),
    initializeWallet,
    syncBalances,
    syncFundingBalances,
    syncTradingBalances,
    syncBankAccounts,
    syncSupportBanks,
  };
});
