import cron from 'node-cron';
import Stripe from 'stripe';
import Payment from '../models/Payment';

/**
 * Initialize the payment monitoring cron job.
 * Runs every hour to check for pending payments and verify their status with Stripe.
 */
export const initFailedPaymentCron = () => {
    // Run immediately on server start
    runPaymentCheck();

    // Schedule task to run at minute 0 past every hour
    cron.schedule('0 * * * *', () => {
        runPaymentCheck();
    });

    console.log('[Cron] Payment status monitoring job scheduled (runs every hour).');
};

const runPaymentCheck = async () => {
    console.log(`[Cron] Running payment status check at ${new Date().toISOString()}...`);

    const stripeSecretKey = process.env.STRIPE_SECRET_KEY;
    if (!stripeSecretKey) {
        console.error('[Cron] STRIPE_SECRET_KEY is missing. Cannot check payment statuses.');
        return;
    }

    const stripe = new Stripe(stripeSecretKey, {
        apiVersion: '2023-10-16' as any,
    });

    try {
        // Find all payments with status 'created' (pending)
        // We only check payments created more than 30 minutes ago to allow time for user completion
        const thirtyMinutesAgo = new Date(Date.now() - 30 * 60 * 1000);

        const pendingPayments = await Payment.find({
            status: 'created',
            createdAt: { $lt: thirtyMinutesAgo }
        });

        if (pendingPayments.length > 0) {
            console.log(`[Cron] Found ${pendingPayments.length} pending payments to check.`);

            for (const payment of pendingPayments) {
                try {
                    const session = await stripe.checkout.sessions.retrieve(payment.sessionId);

                    if (session.status === 'expired') {
                        // Mark as failed in DB
                        payment.status = 'failed';
                        await payment.save();
                        console.log(`[Cron] Marked payment ${payment._id} (Session: ${payment.sessionId}) as failed (Expired).`);
                    } else if (session.status === 'open') {
                        console.log(`[Cron] Payment ${payment._id} (Session: ${payment.sessionId}) is still open.`);
                    }

                } catch (err: any) {
                    console.error(`[Cron] Error checking session ${payment.sessionId}:`, err.message);
                }
            }
        } else {
            console.log('[Cron] No potentially failed payments found to check.');
        }

    } catch (error) {
        console.error('[Cron] Error running payment status check:', error);
    }
};
