/*
 Progressive printer tests via backend endpoints.
 - Starts the Express server by requiring it
 - Sends simple -> complex print jobs to matricial2
*/
process.env.PRINTER_HOST = process.env.PRINTER_HOST || '192.168.87.147';
process.env.PRINTER_DEVICE_ID = process.env.PRINTER_DEVICE_ID || 'matricial2';
process.env.PRINTER_TIMEOUT_MS = process.env.PRINTER_TIMEOUT_MS || '60000';

// Start server
require('../src/server.js');

const axios = require('axios');

async function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }

async function run() {
  const base = 'http://localhost:3000';
  const steps = [];

  steps.push({
    name: 'dryRun minimo',
    path: '/api/print',
    body: { operations: [{ op: 'text', value: 'Hola DRYRUN' }], dryRun: true }
  });

  steps.push({
    name: 'texto simple',
    path: '/api/print/text',
    body: { text: 'Test 1: texto simple', options: { feedLines: 1 } }
  });

  steps.push({
    name: 'alineado + corte',
    path: '/api/print/text',
    body: { text: 'Test 2: center + cut', options: { align: 'center', feedLines: 1, cut: 'feed' } }
  });

  steps.push({
    name: 'fuente y tamaño',
    path: '/api/print/text',
    body: { text: 'Test 3: font_b w2 h2', options: { font: 'font_b', size: { width: 2, height: 2 }, style: { em: true } } }
  });

  steps.push({
    name: 'lote con feeds',
    path: '/api/print',
    body: { operations: [
      { op: 'text', value: 'Test 4: linea 1' },
      { op: 'feedLine', line: 1 },
      { op: 'text', value: 'Test 4: linea 2' }
    ]}
  });

  steps.push({
    name: 'barcode EAN13',
    path: '/api/print',
    body: { operations: [
      { op: 'textAlign', align: 'center' },
      { op: 'text', value: 'Test 5: EAN13' },
      { op: 'feedLine', line: 1 },
      { op: 'barcode', data: '490123456789', type: 'ean13', hri: 'below', width: 3, height: 80 },
      { op: 'feedLine', line: 2 }
    ]}
  });

  steps.push({
    name: 'QR code',
    path: '/api/print',
    body: { operations: [
      { op: 'textAlign', align: 'center' },
      { op: 'text', value: 'Test 6: QR' },
      { op: 'feedLine', line: 1 },
      { op: 'qrcode', data: 'https://example.com/test6', model: 'qrcode_model_2', level: 'level_m', size: 6 },
      { op: 'feedLine', line: 2 }
    ]}
  });

  steps.push({
    name: 'abrir cajon',
    path: '/api/print/pulse',
    body: { drawer: 'drawer_1', time: 'pulse_200' }
  });

  for (const s of steps) {
    try {
      console.log(`\n==> ${s.name}`);
      const resp = await axios.post(base + s.path, s.body, { timeout: 120000 });
      console.log({ status: resp.status, data: resp.data });
      if (resp.data && resp.data.ok === false) {
        console.warn('WARN: backend reported not ok:', resp.data.code || resp.data);
      }
    } catch (e) {
      console.error('ERROR in step', s.name, e.message);
    }
    await sleep(1000);
  }

  console.log('\nPruebas completadas.');
}

sleep(500).then(run);

