
const axios = require("axios");
const { getValidToken } = require("./tokenManager");
const { getAxiosProxyConfig } = require("./requestHelper"); // ? FIXED CIRCULAR DEPENDENCY

async function checkWeeklyLimit(accountId, proxy) {
    try {
        const token = await getValidToken(accountId);
        const response = await axios.get(
            "https://api2.datatwix.com/rewards/v3/receipt/history?voidCache=true",
            {
                headers: { "Authorization": `Bearer ${token}`, "Accept": "application/json" },
                ...getAxiosProxyConfig(proxy)
            }
        );
        return response.data.currentWeekLimit.points;
    } catch (error) {
        console.error(`? Failed to check weekly limit: ${error.response?.status} - ${error.response?.data}`);
        return 0;
    }
}

async function checkHistory(accountId, proxy) {
    try {
        const token = await getValidToken(accountId);
        const response = await axios.get(
            "https://api2.datatwix.com/rewards/v3/receipt/history?voidCache=true",
            {
                headers: { "Authorization": `Bearer ${token}`, "Accept": "application/json" },
                ...getAxiosProxyConfig(proxy)
            }
        );
        return response.data;
    } catch (error) {
        console.error(`? Failed to fetch history: ${error.response?.status} - ${error.response?.data}`);
        return null;
    }
}

async function getRejectedReceipts(accountId, proxy) {
    const history = await checkHistory(accountId, proxy);
    if (!history || !history.receipts) return [];

    return history.receipts.filter(receipt => receipt.status === "REJECTED");
}

async function deleteReceipt(accountId, receiptId, proxy) {
    try {
        const token = await getValidToken(accountId);
        const deleteUrl = `https://api2.datatwix.com/rewards/receipt/${receiptId}`; // ✅ Corrected URL

        console.log(`🗑 Deleting rejected receipt ID: ${receiptId}`);

        const response = await axios.delete(deleteUrl, {
            headers: {
                "Authorization": `Bearer ${token}`,
                "Accept": "application/json, text/plain, */*"
            },
            ...getAxiosProxyConfig(proxy)
        });

        if (response.status === 204) { // ✅ 204 No Content means successful deletion
            console.log(`✅ Successfully deleted receipt ID: ${receiptId}`);
            return true;
        } else {
            console.error(`❌ Unexpected response: ${response.status}`);
            return false;
        }
    } catch (error) {
        console.error(`❌ Failed to delete receipt ${receiptId}: ${error.response?.status} - ${error.response?.data}`);
        return false;
    }
}


module.exports = { checkWeeklyLimit, checkHistory, getRejectedReceipts, deleteReceipt };
