/**
 * Shared helpers for integration tests.
 *
 * Provides config loading and MockWalletAdapter matching the patterns
 * used by tests/wasm/run-tests.mjs, so the same test-env.json and
 * environment variables work across all test suites.
 */
import { existsSync, readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
const __dirname_resolved = dirname(fileURLToPath(import.meta.url));
// Path to the shared test config (same as test-cli / test-wasm)
const CONFIG_DIR = join(__dirname_resolved, '../../../../tests/config');
// Load test secrets from .env.test if available (private keys, superadmin keys, etc.)
try {
    const { config: dotenvConfig } = await import('dotenv');
    dotenvConfig({ path: join(CONFIG_DIR, '.env.test') });
}
catch {
    // dotenv not installed — rely on environment variables directly
}
export function loadTestConfig() {
    const configPath = join(CONFIG_DIR, 'test-env.json');
    const testEnv = process.env.TEST_ENV || 'local';
    let base = {};
    if (existsSync(configPath)) {
        const all = JSON.parse(readFileSync(configPath, 'utf-8'));
        base = all[testEnv] || {};
    }
    // Per-environment env var prefix: uses secretsEnv from config (e.g. "staging-sepolia" -> "SDK_STAGING_SEPOLIA")
    const secretsEnv = base.secretsEnv || testEnv;
    const envPrefix = `SDK_${secretsEnv.replace(/-/g, '_').toUpperCase()}`;
    // Well-known Anvil default accounts for local development (not secrets)
    const anvilDefaults = testEnv.startsWith('local') ? {
        PRIVATE_KEY: '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80',
        ADDRESS: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',
        SECOND_PRIVATE_KEY: '0xe81dcd8d83011671585f2d8783855fa29f7f18a9cec80a03fc367f518f0f84fa',
        SECOND_ADDRESS: '0x2C1A4fc7d07b8487e75F57ef87DC44C9590baAD9',
    } : {};
    const envResolve = (suffix) => process.env[`${envPrefix}_${suffix}`] || process.env[`SDK_${suffix}`] || anvilDefaults[suffix] || '';
    // Auth app ID: env var → test-env.json → auth-test-apps file (generated by setup-auth-apps.sh)
    let appId = process.env.APP_ID || base.appId || '';
    if (!appId) {
        for (const name of [`auth-test-apps.${testEnv}.json`, 'auth-test-apps.json']) {
            const p = join(CONFIG_DIR, name);
            if (existsSync(p)) {
                const apps = JSON.parse(readFileSync(p, 'utf-8'));
                appId = apps.apps?.app_id_only?.app_id || '';
                if (appId)
                    break;
            }
        }
    }
    const accounts = (base.accounts || {});
    const contracts = (base.contracts || {});
    const testAmounts = (base.testAmounts || {});
    const timing = (base.timing || {});
    return {
        serverUrl: process.env.SERVER_URL || base.serverUrl || 'http://localhost:8080',
        rpcUrl: process.env.RPC_URL || base.rpcUrl || 'http://localhost:8545',
        chainId: parseInt(process.env.CHAIN_ID || String(base.chainId || 0), 10) || 0,
        privateKey: envResolve('PRIVATE_KEY'),
        address: envResolve('ADDRESS') || accounts.user1?.address || '',
        secondPrivateKey: envResolve('SECOND_PRIVATE_KEY'),
        secondAddress: envResolve('SECOND_ADDRESS') || accounts.user2?.address || '',
        testToken: process.env.SDK_TEST_TOKEN || contracts.testToken || '',
        wethContractAddress: process.env.SDK_WETH_CONTRACT_ADDRESS || contracts.weth || '',
        appId,
        testAmounts: {
            shieldAmount: testAmounts.shieldAmount || '1000000000000000000',
            unshieldAmount: testAmounts.unshieldAmount || '2000000000000000000',
            transferAmount: testAmounts.transferAmount || '1500000000000000000',
            ethShieldAmount: testAmounts.ethShieldAmount || '1000000000000000',
            ethUnshieldAmount: testAmounts.ethUnshieldAmount || '900000000000000',
        },
        timing: {
            complianceWindow: timing.complianceWindow || 35,
            testTimeout: timing.testTimeout || 120,
        },
    };
}
/**
 * Auto-discover chain config from the indexer's /api/v1/info endpoint.
 */
export async function discoverServerInfo(serverUrl) {
    const resp = await fetch(`${serverUrl}/api/v1/info`);
    if (!resp.ok)
        throw new Error(`/api/v1/info returned ${resp.status}`);
    return resp.json();
}
/**
 * Mock wallet adapter using ethers.js — same pattern as tests/wasm/run-tests.mjs.
 * Implements the WalletBridge interface expected by SDK authenticate().
 */
export async function createMockWallet(privateKey, rpcUrl, chainId) {
    const { ethers } = await import('ethers');
    const provider = new ethers.JsonRpcProvider(rpcUrl);
    const wallet = new ethers.Wallet(privateKey, provider);
    let nonce = null;
    return {
        async connect() { return { address: wallet.address, chainId }; },
        async disconnect() { },
        async getAddress() { return wallet.address; },
        async getChainId() { return chainId; },
        async signMessage(message) { return wallet.signMessage(message); },
        async signTypedData(typedDataJson) {
            const td = JSON.parse(typedDataJson);
            const types = { ...td.types };
            delete types.EIP712Domain;
            return wallet.signTypedData(td.domain, types, td.message);
        },
        async readContract(contractAddress, data) {
            return provider.call({ to: contractAddress, data });
        },
        async sendTransaction(tx) {
            if (nonce === null) {
                nonce = await provider.getTransactionCount(wallet.address, 'pending');
            }
            const currentNonce = nonce;
            try {
                const resp = await wallet.sendTransaction({
                    to: tx.to || tx.toAddress,
                    value: tx.value || '0',
                    data: tx.data || '0x',
                    nonce: currentNonce,
                });
                nonce++;
                await resp.wait(1);
                return resp.hash;
            }
            catch (err) {
                nonce = null;
                throw err;
            }
        },
        async waitForTransactionReceipt(txHash) {
            const receipt = await provider.waitForTransaction(txHash, 1);
            return {
                status: receipt.status === 1 ? 'success' : 'reverted',
                transactionHash: receipt.hash,
                logs: receipt.logs.map((log) => ({
                    address: log.address,
                    topics: [...log.topics],
                    data: log.data,
                })),
            };
        },
    };
}
export function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
//# sourceMappingURL=test-helpers.js.map