// Consolidated chain-switch handler.
//
// Every state change required when the active network changes is
// performed here so that callers (settings UI, background
// wallet_switchEthereumChain, future chain additions) all go
// through a single code path.
//
// Adding a new chain (e.g. ETC) requires only a new entry in
// networks.js — no per-caller wiring is needed.

const { networkById } = require("./networks");
const { clearPrices } = require("./prices");

// Switch the active chain and reset all chain-specific cached state.
// Returns the network configuration object for the new chain.
async function onChainSwitch(newNetworkId) {
    const { state, saveState } = require("./state");

    const net = networkById(newNetworkId);

    // --- core identity ---
    state.networkId = net.id;
    state.rpcUrl = net.defaultRpcUrl;
    state.blockscoutUrl = net.defaultBlockscoutUrl;

    // --- price cache ---
    // Prices are chain-specific (testnet tokens are worthless,
    // ETC has different pricing, etc.).
    clearPrices();

    // --- balance / refresh state ---
    // Reset last-refresh timestamp so the next polling cycle
    // triggers an immediate balance refresh on the new chain.
    state.lastBalanceRefresh = 0;

    // Clear per-address balances and token balances so stale data
    // from the previous chain is never displayed while the first
    // refresh on the new chain is in flight.
    for (const wallet of state.wallets) {
        for (const addr of wallet.addresses) {
            addr.balance = "0";
            addr.tokenBalances = [];
        }
    }

    // --- chain-specific caches ---
    // Token holder counts and fraud contract lists are
    // chain-specific and must not carry over.
    state.tokenHolderCache = {};
    state.fraudContracts = [];

    await saveState();

    return net;
}

module.exports = { onChainSwitch };
