const { startSync, getSyncStatus } = require('/root/HoruxDespachosNuevo/apps/api/dist/services/sat/sat.service.js');

const TENANT_ID = '81116985-03cd-4843-97ba-05e8be9917c6';
const DAYS = 15;

async function main() {
  const dateTo = new Date();
  const dateFrom = new Date(dateTo);
  dateFrom.setDate(dateFrom.getDate() - DAYS);

  console.log(`[Test] Iniciando sync initial para AUZA640701TI9`);
  console.log(`[Test] Rango: ${dateFrom.toISOString().slice(0,10)} → ${dateTo.toISOString().slice(0,10)}`);

  try {
    const jobId = await startSync(TENANT_ID, 'initial', dateFrom, dateTo);
    console.log(`[Test] Job creado: ${jobId}`);

    // Monitorear progreso
    let completed = false;
    let attempts = 0;
    const maxAttempts = 60; // ~30 minutos (30s * 60)

    while (!completed && attempts < maxAttempts) {
      await new Promise(r => setTimeout(r, 30000));
      attempts++;

      const status = await getSyncStatus(TENANT_ID);
      console.log(`[Test] Intento ${attempts}: status=${status.currentJob?.status || 'none'}, progress=${status.currentJob?.progressPercent ?? 0}%, found=${status.currentJob?.cfdisFound ?? 0}, inserted=${status.currentJob?.cfdisInserted ?? 0}`);

      if (!status.hasActiveSync) {
        completed = true;
        console.log(`[Test] Sync finalizado. Último job: ${status.lastCompletedJob?.status || 'N/A'}`);
        if (status.lastCompletedJob?.errorMessage) {
          console.log(`[Test] Error: ${status.lastCompletedJob.errorMessage}`);
        }
      }
    }

    if (!completed) {
      console.log(`[Test] Timeout después de ${maxAttempts} intentos. El job sigue corriendo.`);
    }
  } catch (err) {
    console.error(`[Test] Error iniciando sync:`, err.message);
  }
}

main().catch(console.error);
