const mysql = require("mysql2/promise");
const printer = require("pdf-to-printer");
const path = require("path");
const fs = require("fs");
const config = require("./config");

console.log("📁 __dirname =", __dirname);
console.log("📁 config chargé depuis :", require.resolve("./config"));

console.log("📂 Working directory :", process.cwd());

(async () => {
  const db = await mysql.createPool(config.db);
  console.log("🟢 POS PDF Printer Agent démarré");

  async function processJobs() {
    try {
      const [jobs] = await db.query(`
        SELECT pj.*
        FROM print_jobs pj
        WHERE pj.statut = 'pending'
        ORDER BY pj.id ASC
        LIMIT 1
      `);

      if (!jobs.length) return;

      const job = jobs[0];
      const printerConfig = config.printers[job.print_code];
      const printerName = printerConfig ? printerConfig.name : null;
      if (!printerName) {
        await failJob(job.id, "Imprimante non configurée");
        return;
      }

      const pdfPath = path.join(
        __dirname,
        "..",
        "pages",
        "rapports",
        "pos",
        "output",
        `ticket_${job.vente_id}.pdf`
      );

      console.log(`🔍 Job #${job.id}`);
      console.log("📄 PDF :", pdfPath);
      console.log("🧾 Imprimante :", printerName);

      // ⏳ PDF PAS ENCORE GÉNÉRÉ → ON ATTEND
      if (!fs.existsSync(pdfPath)) {
        console.log(`⏳ PDF pas encore prêt (vente #${job.vente_id})`);
        return;
      }

      console.log(`🖨 Impression en cours (job #${job.id})`);

      await printer.print(pdfPath, {
        printer: printerName,
        win32: ['-print-settings "fit"']
      });

      await db.query(
        "UPDATE print_jobs SET statut='printed', printed_at=NOW() WHERE id=?",
        [job.id]
      );

      console.log(`✅ Impression réussie (job #${job.id})`);

    } catch (err) {
      console.error("❌ Agent error :", err.message || err);
    }
  }

  async function failJob(id, message) {
    await db.query(
      "UPDATE print_jobs SET statut='failed', error_message=? WHERE id=?",
      [message, id]
    );
    console.log(`❌ Job #${id} failed : ${message}`);
  }

  setInterval(processJobs, config.pollIntervalMs);
})();
