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

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

function ensureDir(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}

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

async function runBulkInventorySyncJob() {
  logStep('Bulk Caller Job', 'JOB STARTED');

  const jsonData = JSON.parse(fs.readFileSync(filePath, 'utf8'));
  const shops = Object.entries(jsonData);

  // Process shops sequentially to avoid hammering Turn14 with parallel requests
  for (const [shopDomain, details] of shops) {
    const SHOP = shopDomain.trim();
    const ACCESS_TOKEN = details.accessToken;
    const fulfillmentServiceTokens = details.fulfillmentService || {};
    const FULFILLMENTSERVICEID = fulfillmentServiceTokens.id || null;
    const LOCATIONID = details.locationId || null;

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

    try {
      await syncTurn14Inventory(SHOP, ACCESS_TOKEN, FULFILLMENTSERVICEID, LOCATIONID);
    } catch (err) {
      logStep('Bulk Caller Job', `❌ Unexpected error for ${SHOP}: ${err.message}`);
    }
  }

  logStep('Bulk Caller Job', 'JOB COMPLETED');
}

// Schedule: every 3 hours and 50 minutes
const INTERVAL_MS = (3 * 60 + 50) * 60 * 1000;

function scheduleEvery3Hrs50Mins() {
  runBulkInventorySyncJob().catch(err => {
    console.error('[Scheduler] Unhandled error in job run:', err.message);
  });

  setInterval(() => {
    runBulkInventorySyncJob().catch(err => {
      console.error('[Scheduler] Unhandled error in job run:', err.message);
    });
  }, INTERVAL_MS);
}

scheduleEvery3Hrs50Mins();
