/**
 * Wait until PostgreSQL accepts connections.
 * Usage: node scripts/wait-for-db.mjs
 */
import postgres from "postgres";

const url = process.env.DATABASE_URL;
if (!url) {
  console.error("[wait-for-db] DATABASE_URL is required");
  process.exit(1);
}

const attempts = Number(process.env.DB_WAIT_ATTEMPTS ?? 30);
const delayMs = Number(process.env.DB_WAIT_DELAY_MS ?? 2000);

async function sleep(ms) {
  await new Promise((resolve) => setTimeout(resolve, ms));
}

for (let i = 1; i <= attempts; i += 1) {
  const sql = postgres(url, { max: 1, connect_timeout: 5 });
  try {
    await sql`select 1`;
    await sql.end({ timeout: 1 });
    console.info(`[wait-for-db] ready (attempt ${i}/${attempts})`);
    process.exit(0);
  } catch (error) {
    await sql.end({ timeout: 1 }).catch(() => {});
    const message = error instanceof Error ? error.message : String(error);
    console.warn(
      `[wait-for-db] attempt ${i}/${attempts} failed: ${message}`,
    );
    if (i === attempts) {
      console.error("[wait-for-db] database never became ready");
      process.exit(1);
    }
    await sleep(delayMs);
  }
}
