/**
 * Cleanup Utility for Stale Orders
 * 
 * This script marks very old orders (>24 hours) that are still in pending_new status
 * as 'unknown' or 'expired' to clean up the database.
 * 
 * Usage: npm run cleanup-stale-orders
 */

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

async function cleanupStaleOrders() {
    logger.info('[Cleanup] Starting stale order cleanup...');

    try {
        // Get orders older than 24 hours in pending_new status
        const veryOldOrders = await supabaseService.getStaleOrders(24 * 60); // 24 hours in minutes

        if (!veryOldOrders || veryOldOrders.length === 0) {
            logger.info('[Cleanup] No very old stale orders found. Database is clean! ✅');
            return;
        }

        logger.info(`[Cleanup] Found ${veryOldOrders.length} orders older than 24 hours in pending_new status`);

        let updated = 0;
        for (const order of veryOldOrders) {
            const orderId = order.order_id || order.id;
            const createdAt = new Date(order.created_at);
            const ageHours = Math.floor((Date.now() - createdAt.getTime()) / (1000 * 60 * 60));

            logger.info(`[Cleanup] Marking order ${orderId} as 'unknown' (age: ${ageHours}h, symbol: ${order.symbol})`);

            await supabaseService.updateOrderStatus?.(orderId, 'unknown');
            updated++;
        }

        logger.info(`[Cleanup] ✅ Cleanup complete! Updated ${updated} stale orders to 'unknown' status`);

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

    process.exit(0);
}

// Run cleanup
cleanupStaleOrders();
