const { describe, it, before, after } = require("node:test");
const assert = require("node:assert");
const fs = require("fs");
const path = require("path");
const os = require("os");

const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "siraya-print-test-"));

process.env.PRINT_DATA_DIR = path.join(tmpDir, "queue");
process.env.PRINT_MAX_ATTEMPTS = "2";

const printed = [];

const {
  initQueue,
  acceptPrintJob,
  getJob,
  queueDepth,
  flushQueue,
} = require("../lib/print-queue");

before(() => {
  initQueue({
    printFn: async (job) => {
      printed.push(job.printJobId);
    },
  });
});

describe("print queue", () => {
  it("accepts v1 job and dedupes idempotency", async () => {
    const body = {
      schemaVersion: 1,
      printJobId: "test-job-00000001",
      receiptKind: "customer_receipt",
      templateVersion: 1,
      idempotencyKey: "idem-1",
      payload: { orderNumber: "1", items: [], subtotal: 0, total: 0 },
    };
    const a = acceptPrintJob(body, { legacy: false });
    const b = acceptPrintJob(body, { legacy: false });
    assert.strictEqual(a.printJobId, "test-job-00000001");
    assert.strictEqual(b.deduped, true);
    await new Promise((r) => setTimeout(r, 300));
    const j = getJob("test-job-00000001");
    assert.ok(j);
    assert.strictEqual(printed.filter((id) => id === "test-job-00000001").length, 1);
  });

  it("legacy accept enqueues job", () => {
    const out = acceptPrintJob(
      { orderNumber: "L1", items: [], subtotal: 0, total: 0 },
      { legacy: true },
    );
    assert.ok(out.printJobId.startsWith("legacy-"));
    assert.ok(queueDepth() >= 0);
  });
});

after(async () => {
  await flushQueue();
  await new Promise((r) => setTimeout(r, 100));
  fs.rmSync(tmpDir, { recursive: true, force: true });
});
