"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const env_js_1 = require("../config/env.js");
const connection_js_1 = require("../infrastructure/database/connection.js");
const Crypto_js_1 = require("../infrastructure/payments/Crypto.js");
const PaymentSweeper_js_1 = require("../infrastructure/payments/PaymentSweeper.js");
const Logger_js_1 = require("../shared/logger/Logger.js");
const config = (0, env_js_1.loadEnv)();
const logger = new Logger_js_1.Logger(config.logLevel);
const serializeError = (error) => {
    if (error instanceof Error) {
        return { name: error.name, message: error.message };
    }
    return { error: String(error) };
};
async function main() {
    if (!config.mongoUri) {
        logger.error("MONGO_URI is not configured; cannot sweep payments.");
        return 1;
    }
    if (!config.paymentEncryptionSecret) {
        logger.error("PAYMENT_ENCRYPTION_SECRET is not configured; cannot decrypt payment wallets.");
        return 1;
    }
    const connected = await (0, connection_js_1.connectDatabase)(config.mongoUri, logger);
    if (!connected) {
        logger.error("Failed to connect to the database.");
        return 1;
    }
    try {
        const cryptoBox = new Crypto_js_1.CryptoBox(config.paymentEncryptionSecret);
        const sweeper = new PaymentSweeper_js_1.PaymentSweeper(config, cryptoBox, logger);
        if (!sweeper.isConfigured()) {
            logger.warn("Sweep is not configured. Set EVM_VAULT_ADDRESS and/or TRON_VAULT_ADDRESS to enable it.");
            return 0;
        }
        const summary = await sweeper.sweepUnsweptTransactions();
        logger.info("Sweep summary.", {
            processed: summary.processed,
            swept: summary.swept,
            skipped: summary.skipped,
            failed: summary.failed,
            totalAmount: summary.totalAmount
        });
        return summary.failed > 0 ? 2 : 0;
    }
    catch (error) {
        logger.error("Unexpected error during payment sweep.", serializeError(error));
        return 1;
    }
    finally {
        await (0, connection_js_1.disconnectDatabase)();
    }
}
main()
    .then((exitCode) => {
    process.exitCode = exitCode;
})
    .catch((error) => {
    logger.error("Unexpected error during payment sweep.", serializeError(error));
    process.exitCode = 1;
});
