/**
 * Shared PgBoss singleton — kept in its own module to break circular imports
 * between workert.ts and the worker modules that call getBoss().
 */
import { PgBoss } from "pg-boss";

function makePgBossUrl(rawUrl: string): string {
  try {
    const u = new URL(rawUrl);
    // 30-second statement timeout to prevent individual SQL queries from
    // hanging indefinitely if the DB server stops responding mid-query.
    u.searchParams.set("options", "-c statement_timeout=30000");
    return u.toString();
  } catch {
    return rawUrl;
  }
}

export const boss = new PgBoss({
  connectionString: makePgBossUrl(process.env.DATABASE_URL!),
  connectionTimeoutMillis: 15_000,
});

boss.on("error", (err) => {
  console.error("[worker] PgBoss error", err);
});

export function getBoss(): PgBoss {
  return boss;
}
