import pg from 'pg';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createPool, query } from '../pool.js';
import { getTestDbUrl, recreateDatabase, runMigrations } from './db-test-support.js';

const hasDb = Boolean(process.env.TEST_DATABASE_URL);

describe.skipIf(!hasDb)('db pool', () => {
  const url = hasDb ? getTestDbUrl() : '';
  let pool: pg.Pool;

  beforeAll(async () => {
    await recreateDatabase(url);
    await runMigrations(url, 'up');
    pool = createPool(url);
  });

  afterAll(async () => {
    await pool.end();
  });

  it('connects and runs a trivial query', async () => {
    const result = await query(pool, 'SELECT 1 AS ok');
    expect(result.rows[0]?.ok).toBe(1);
  });

  it('supports a full roundtrip on app_meta via the query helper', async () => {
    await query(pool, 'INSERT INTO app_meta (key, value) VALUES ($1, $2)', ['k1', 'v1']);
    const read = await query(pool, 'SELECT value FROM app_meta WHERE key = $1', ['k1']);
    expect(read.rows[0]?.value).toBe('v1');
    await query(pool, 'DELETE FROM app_meta WHERE key = $1', ['k1']);
    const gone = await query(pool, 'SELECT value FROM app_meta WHERE key = $1', ['k1']);
    expect(gone.rowCount).toBe(0);
  });

  it('rejects an empty connection string', () => {
    expect(() => createPool('')).toThrowError(/connection string is required/);
  });
});
