import pg from 'pg';

const { Pool } = pg;

let pool: pg.Pool | null = null;

export function getPool(databaseUrl: string): pg.Pool {
  if (pool) return pool;
  pool = new Pool({ connectionString: databaseUrl, max: 5, idleTimeoutMillis: 30_000 });
  return pool;
}

interface SessionInfo {
  id: string;
  project_id: string;
  project_path: string;
  name: string | null;
}

export async function getSessionInfo(sessionId: string): Promise<SessionInfo | null> {
  if (!pool) throw new Error('db pool not initialized');
  const res = await pool.query<SessionInfo>(
    `SELECT s.id, s.project_id, p.path AS project_path, s.name
     FROM sessions s
     JOIN projects p ON p.id = s.project_id
     WHERE s.id = $1`,
    [sessionId],
  );
  return res.rows[0] ?? null;
}

export async function pingDb(): Promise<boolean> {
  if (!pool) return false;
  try {
    await pool.query('SELECT 1');
    return true;
  } catch {
    return false;
  }
}

export async function closeDb(): Promise<void> {
  if (pool) {
    await pool.end();
    pool = null;
  }
}
