// smartflow-api.js

function getBaseConfig() {
    const boot = window.ACC_APP_BOOT;

    if (!boot) {
        throw new Error('ACC_APP_BOOT is not defined');
    }

    let restBase = boot.restBase || '';
    restBase = restBase.replace(/\/?$/, '/');

    return {
        apiRoot: restBase + 'acc/v1/',
        nonce: boot.nonce || '',
    };
}

export async function fetchVoucherRaw(voucherId) {
    const { apiRoot } = getBaseConfig();
    const url = `${apiRoot}voucher/${encodeURIComponent(voucherId)}/raw`;

    console.log('Fetching SmartFlow URL:', url);

    const res = await fetch(url, {
        method: 'GET',
        credentials: 'same-origin',
        headers: {
            'Accept': 'application/json'
            // ⛔ عمداً X-WP-Nonce را برای GET نمی‌فرستیم
        },
    });

    if (!res.ok) {
        let errorText = '';
        try {
            errorText = await res.text();
        } catch (e) {
            errorText = 'Unknown error';
        }

        throw new Error(`Failed to fetch voucher raw: ${res.status} - ${errorText}`);
    }

    return await res.json();
}
