import { spawn } from "node:child_process";
import { createRequire } from "node:module";
import path from "node:path";
import { drainQueueFromAppRoot } from "./queue-runner.js";
const DEFAULT_JOB_LIMIT = 100;
function resolveAppRoot(input) {
  return path.resolve(input?.trim() || process.env.OM_TEST_APP_ROOT?.trim() || path.resolve(process.cwd(), "apps/mercato"));
}
async function drainQueueInCurrentProcess(queueName, options) {
  return drainQueueFromAppRoot(queueName, options);
}
function resolveAppRunnerPath(appRoot) {
  const requireFromApp = createRequire(path.join(appRoot, "package.json"));
  return requireFromApp.resolve("@open-mercato/core/helpers/integration/queue-runner");
}
function drainQueueInAppProcess(queueName, options) {
  return new Promise((resolve, reject) => {
    const child = spawn(process.execPath, [resolveAppRunnerPath(options.appRoot)], {
      cwd: options.appRoot,
      env: {
        ...process.env,
        OM_INTEGRATION_APP_ROOT: options.appRoot,
        OM_INTEGRATION_QUEUE_NAME: queueName,
        OM_INTEGRATION_QUEUE_JOB_LIMIT: String(options.jobLimit),
        QUEUE_BASE_DIR: process.env.QUEUE_BASE_DIR?.trim() || path.resolve(options.appRoot, ".mercato/queue")
      },
      stdio: ["ignore", "pipe", "pipe"]
    });
    let stdout = "";
    let stderr = "";
    child.stdout.on("data", (chunk) => {
      stdout += chunk.toString();
    });
    child.stderr.on("data", (chunk) => {
      stderr += chunk.toString();
    });
    child.on("error", reject);
    child.on("close", (code) => {
      if (process.env.OM_DRAIN_DEBUG === "1") {
        process.stderr.write(`[drain-child ${queueName} exit=${code}] STDOUT:
${stdout}
STDERR:
${stderr}
`);
      } else if (stderr.trim().length > 0) {
        process.stderr.write(`[drain-child ${queueName} exit=${code}] STDERR:
${stderr}
`);
      }
      if (code !== 0) {
        reject(new Error(`Queue drain failed for "${queueName}" in ${options.appRoot} (exit ${code}).
${stderr || stdout}`));
        return;
      }
      const lastLine = stdout.trim().split(/\r?\n/).reverse().find((line) => line.trim().startsWith("{")) ?? "{}";
      try {
        const parsed = JSON.parse(lastLine);
        resolve(Number(parsed.processed ?? 0));
      } catch {
        resolve(0);
      }
    });
  });
}
async function drainIntegrationQueue(queueName, options = {}) {
  const resolved = {
    appRoot: resolveAppRoot(options.appRoot),
    jobLimit: options.jobLimit ?? DEFAULT_JOB_LIMIT
  };
  if (process.env.OM_TEST_APP_ROOT?.trim()) {
    return drainQueueInAppProcess(queueName, resolved);
  }
  return drainQueueInCurrentProcess(queueName, resolved);
}
export {
  drainIntegrationQueue
};
//# sourceMappingURL=queue.js.map
