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

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() {
    const jsonData = JSON.parse(fs.readFileSync(filePath, 'utf8'));

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

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

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

    const intervalMs = (3 * 60 + 40) * 60 * 1000; // 13200000 ms = 3hr 40min
    setInterval(runBulkInventorySyncJob, intervalMs);
}

scheduleEvery3Hrs40Mins();
