const fs = require('fs');
const path = require('path');
const { syncTurn14Inventory } = require('./InventorySync');

const filePath = path.join(__dirname, '..', 'data', 'tokens.json');
const logFilePath = path.join(__dirname, '..', 'logs', 'BulkInventorySyncJob.log');

function logStep(step, message) {
    const logMessage = `[${new Date().toISOString()}] [${step}] ${message}`;
    console.log(logMessage);
    fs.appendFileSync(logFilePath, logMessage + '\n', 'utf8');
}

function runBulkInventorySyncJob() {
    logStep('Bulk Caller Job', `JOB STARTED`);
    const jsonData = JSON.parse(fs.readFileSync(filePath, 'utf8'));

    Object.entries(jsonData).forEach(([shopDomain, details]) => {
        const SHOP = shopDomain.trim();
        const ACCESS_TOKEN = details.accessToken;

        const fulfillmentServiceTokens = details.fulfillmentService || {}
        const FULFILLMENTSERVICEID = fulfillmentServiceTokens.id || null;
        // const LOCATIONID = fulfillmentServiceTokens.location ? fulfillmentServiceTokens.location.id : null;
        const LOCATIONID = details.locationId ? details.locationId : null;

        console.log("Location ID : ", LOCATIONID)

        logStep('Bulk Caller Job', `Syncing inventory for: ${SHOP}`);
        syncTurn14Inventory(SHOP, ACCESS_TOKEN, FULFILLMENTSERVICEID, LOCATIONID);
    });
    // logStep('Bulk Caller Job', `JOB COMPLETED`);
}

// ⏱ Schedule: every 3 hours and 40 minutes
function scheduleEvery3Hrs40Mins() {
    runBulkInventorySyncJob(); // Run immediately on start

    var intervalMs = (3 * 60 + 50) * 60 * 1000; // 13200000 ms = 3hr 50min
    //intervalMs = (1 * 60 - 10) * 60 * 1000; // 13200000 ms = 3hr 40min
    setInterval(runBulkInventorySyncJob, intervalMs);
}

scheduleEvery3Hrs40Mins();
