/**
 * Revert Expired/Unknown Orders Script
 * 
 * Reverts orders marked as 'expired' or 'unknown' back to 'pending_new'.
 * This is useful if you want to retry syncing them or prefer them showing as 'stale'
 * rather than 'expired'.
 * 
 * Usage: npm run revert-expired-orders
 */

import { supabaseService } from '../services/SupabaseService.js';
import logger from '../utils/logger.js';

async function revertExpiredOrders() {
    logger.info('[Revert] Starting to revert expired/unknown orders...');

    try {
        // Find orders with status 'expired' or 'unknown'
        const expiredOrders = await supabaseService.getExpiredOrUnknownOrders();

        if (!expiredOrders || expiredOrders.length === 0) {
            logger.info('[Revert] No expired or unknown orders found. Nothing to do! ✅');
            process.exit(0);
        }

        logger.info(`[Revert] Found ${expiredOrders.length} orders marked as 'expired' or 'unknown'`);

        let updated = 0;
        for (const order of expiredOrders) {
            const orderId = order.order_id || order.id;

            logger.info(`[Revert] Reverting order ${orderId} (${order.symbol}) to 'pending_new'`);

            // Use updateOrderStatus to reset status
            // Note: filledAt is undefined since we are resetting to pending
            await supabaseService.updateOrderStatus?.(orderId, 'pending_new');
            updated++;
        }

        logger.info(`[Revert] ✅ Successfully reverted ${updated} orders to 'pending_new'.`);

    } catch (error: any) {
        logger.error(`[Revert] Error: ${error.message}`);
        process.exit(1);
    }

    process.exit(0);
}

revertExpiredOrders();
