"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ArbitrageCustomPriceCleanupWorker = void 0;
const ArbitrageCustomPriceModel_js_1 = require("../../infrastructure/database/models/ArbitrageCustomPriceModel.js");
class ArbitrageCustomPriceCleanupWorker {
    platformRepository;
    getAdminJwt;
    logger;
    interval;
    constructor(platformRepository, getAdminJwt, logger) {
        this.platformRepository = platformRepository;
        this.getAdminJwt = getAdminJwt;
        this.logger = logger;
    }
    async schedule(record) {
        try {
            await ArbitrageCustomPriceModel_js_1.ArbitrageCustomPriceModel.create(record);
        }
        catch (error) {
            this.logger.error("Could not schedule arbitrage custom-price cleanup.", {
                tokenId: record.tokenId,
                error: error instanceof Error ? error.message : String(error)
            });
        }
    }
    start(intervalMs = 60_000) {
        if (this.interval)
            return;
        this.interval = setInterval(() => {
            this.tick().catch((error) => {
                this.logger.error("Unhandled error in arbitrage cleanup worker tick.", {
                    error: error instanceof Error ? error.message : String(error),
                    stack: error instanceof Error ? error.stack : undefined
                });
            });
        }, intervalMs);
        this.interval.unref();
    }
    stop() {
        if (this.interval) {
            clearInterval(this.interval);
            this.interval = undefined;
        }
    }
    async tick() {
        let jwt;
        try {
            jwt = await this.getAdminJwt.execute();
        }
        catch (error) {
            this.logger.error("Could not fetch admin JWT for custom-price cleanup.", {
                error: error instanceof Error ? error.message : String(error)
            });
            return;
        }
        let due = [];
        try {
            due = await ArbitrageCustomPriceModel_js_1.ArbitrageCustomPriceModel.find({
                expiresAt: { $lte: new Date() },
                clearedAt: { $exists: false }
            }).limit(50);
        }
        catch (error) {
            this.logger.error("Could not fetch due arbitrage cleanup records.", {
                error: error instanceof Error ? error.message : String(error)
            });
            return;
        }
        if (due.length === 0)
            return;
        let activeCustomPrices = [];
        try {
            activeCustomPrices = await this.platformRepository.getCustomPrices(jwt);
        }
        catch (error) {
            this.logger.error("Could not fetch active custom prices for cleanup check.", {
                error: error instanceof Error ? error.message : String(error)
            });
        }
        await Promise.allSettled(due.map(async (record) => {
            try {
                const current = activeCustomPrices.find((cp) => cp.tokenId === record.tokenId);
                // Only clear if the token still has a trailing custom price with the same gap we set.
                if (current && current.priceType === "trailing" && current.priceGap === record.priceGap) {
                    await this.platformRepository.clearCustomPrice(record.tokenId, jwt);
                }
                await ArbitrageCustomPriceModel_js_1.ArbitrageCustomPriceModel.updateOne({ _id: record._id }, { $set: { clearedAt: new Date() } });
            }
            catch (error) {
                this.logger.error(`Failed to clear custom price for ${record.tokenSymbol} (${record.tokenId}).`, {
                    error: error instanceof Error ? error.message : String(error)
                });
            }
        }));
    }
}
exports.ArbitrageCustomPriceCleanupWorker = ArbitrageCustomPriceCleanupWorker;
