const axios = require("axios");
const { getValidToken } = require("./tokenManager");

async function getRejectedReceipts(accountId, proxy) {
    try {
        const token = await getValidToken(accountId);
        const response = await axios.get(
            "https://api2.datatwix.com/rewards/receipts/history",
            {
                headers: {
                    "Authorization": `Bearer ${token}`,
                    "Accept": "application/json"
                },
                proxy: false // Use proxy only if needed
            }
        );

        const receipts = response.data.receipts || [];
        const rejectedReceipts = receipts.filter(r => r.status === "REJECTED");

        console.log(`?? Found ${rejectedReceipts.length} rejected receipts.`);
        return rejectedReceipts.map(r => r.id);
    } catch (error) {
        console.error(`? Failed to fetch history: ${error.message}`);
        return [];
    }
}

async function deleteRejectedReceipt(accountId, receiptId, proxy) {
    try {
        const token = await getValidToken(accountId);
        await axios.delete(
            `https://api2.datatwix.com/rewards/receipt/${receiptId}`,
            {
                headers: {
                    "Authorization": `Bearer ${token}`,
                    "Accept": "application/json"
                },
                proxy: false // Use proxy only if needed
            }
        );

        console.log(`? Deleted rejected receipt ID: ${receiptId}`);
    } catch (error) {
        console.error(`? Failed to delete receipt ${receiptId}: ${error.message}`);
    }
}

async function processRejectedReceipts(accountId, proxy) {
    console.log(`?? Checking for rejected receipts for account ID ${accountId}...`);

    const rejectedIds = await getRejectedReceipts(accountId, proxy);

    for (const receiptId of rejectedIds) {
        await deleteRejectedReceipt(accountId, receiptId, proxy);
        await new Promise(resolve => setTimeout(resolve, 3000)); // 3-sec delay
    }

    console.log(`? Finished processing rejected receipts for account ${accountId}.`);
}

module.exports = { processRejectedReceipts };