import pg from 'pg';
const { Pool } = pg;

const {
  PGHOST = 'db',
  PGPORT = 5432,
  PGUSER = 'postgres',
  PGPASSWORD = 'postgres',
  PGDATABASE = 'supersunday',
} = process.env;

const pool = new Pool({ host: PGHOST, port: PGPORT, user: PGUSER, password: PGPASSWORD, database: PGDATABASE });

export async function waitForDb(retries = 30, delayMs = 2000) {
  for (let i = 1; i <= retries; i++) {
    try {
      await pool.query('select 1');
      return;
    } catch (e) {
      console.log(`[DB] attempt ${i}/${retries} failed: ${e.message}`);
      await new Promise(r => setTimeout(r, delayMs));
    }
  }
  throw new Error('DB not reachable after retries');
}

export default pool;