"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchFundLedger = fetchFundLedger;
exports.fetchOfficeProfile = fetchOfficeProfile;
exports.auditSwapToSettlement = auditSwapToSettlement;
exports.requestM2TokenLoad = requestM2TokenLoad;
exports.requestInternalTransfer = requestInternalTransfer;
exports.requestExternalTransfer = requestExternalTransfer;
exports.fetchCryptoLedger = fetchCryptoLedger;
exports.resolveTokenLine = resolveTokenLine;
const axios_1 = __importDefault(require("axios"));
const ethers_1 = require("ethers");
const config_1 = require("../config");
const ERC20_ABI = ['function balanceOf(address) view returns (uint256)', 'function decimals() view returns (uint8)'];
async function fetchFundLedger(officeId, apiKey) {
    const headers = {};
    if (apiKey)
        headers.Authorization = `Bearer ${apiKey}`;
    const { data } = await axios_1.default.get(`${(0, config_1.settlementUrl)()}/api/v1/settlement/money-supply`, {
        headers,
        timeout: 60000,
    });
    return { officeId, fundLedger: data };
}
async function fetchOfficeProfile() {
    const { data } = await axios_1.default.get(`${(0, config_1.settlementUrl)()}/api/v1/settlement/office`, { timeout: 15000 });
    return data;
}
async function auditSwapToSettlement(payload) {
    const lineId = payload.tokenLineId ?? `${payload.currency}-M2`;
    const headers = { 'Content-Type': 'application/json' };
    if (payload.apiKey)
        headers.Authorization = `Bearer ${payload.apiKey}`;
    const { data } = await axios_1.default.post(`${(0, config_1.settlementUrl)()}/api/v1/settlement/convert/fiat-to-crypto`, {
        idempotencyKey: payload.idempotencyKey,
        amount: payload.amount,
        currency: payload.currency,
        creditorIban: 'GB82WEST12345698765432',
        beneficiaryName: 'DBIS Exchange settlement audit',
        remittanceInfo: payload.remittanceInfo,
        convertToCrypto: {
            enabled: true,
            targetChainId: 138,
            tokenLineId: lineId,
            recipientAddress: payload.recipientAddress,
        },
    }, { headers, timeout: 120000, validateStatus: () => true });
    return data;
}
async function requestM2TokenLoad(payload) {
    const headers = { 'Content-Type': 'application/json' };
    if (payload.apiKey)
        headers.Authorization = `Bearer ${payload.apiKey}`;
    const { data } = await axios_1.default.post(`${(0, config_1.settlementUrl)()}/api/v1/settlement/token-load`, {
        idempotencyKey: payload.idempotencyKey,
        lineId: payload.lineId,
        symbol: payload.symbol,
        tokenAddress: payload.tokenAddress,
        amount: payload.amount,
        recipientAddress: payload.recipientAddress,
        currency: payload.currency,
    }, { headers, timeout: 120000, validateStatus: () => true });
    return data;
}
async function requestInternalTransfer(payload) {
    const headers = { 'Content-Type': 'application/json' };
    if (payload.apiKey)
        headers.Authorization = `Bearer ${payload.apiKey}`;
    const { data } = await axios_1.default.post(`${(0, config_1.settlementUrl)()}/api/v1/settlement/transfer/internal`, {
        ...payload,
        moneyLayers: ['M2'],
    }, { headers, timeout: 120000, validateStatus: () => true });
    return data;
}
async function requestExternalTransfer(payload) {
    const headers = { 'Content-Type': 'application/json' };
    if (payload.apiKey)
        headers.Authorization = `Bearer ${payload.apiKey}`;
    const { data } = await axios_1.default.post(`${(0, config_1.settlementUrl)()}/api/v1/settlement/transfer/external`, {
        ...payload,
        moneyLayers: ['M2'],
        rail: 'SWIFT',
    }, { headers, timeout: 120000, validateStatus: () => true });
    return data;
}
async function fetchCryptoLedger(rpcUrl, wallet, tokens) {
    const provider = new ethers_1.JsonRpcProvider(rpcUrl);
    const balances = {};
    for (const t of tokens) {
        if (t.native || t.address === '0x0000000000000000000000000000000000000000') {
            const wei = await provider.getBalance(wallet);
            balances[t.symbol] = (0, ethers_1.formatUnits)(wei, 18);
            continue;
        }
        try {
            const c = new ethers_1.Contract(t.address, ERC20_ABI, provider);
            const raw = await c.balanceOf(wallet);
            balances[t.symbol] = (0, ethers_1.formatUnits)(raw, t.decimals);
        }
        catch {
            balances[t.symbol] = '0';
        }
    }
    return { wallet, balances };
}
function resolveTokenLine(token) {
    return token.omnlLine;
}
