import { execFileSync } from 'node:child_process';

const CONTAINER = process.env.E2E_PG_CONTAINER ?? 'banatie-postgres-dev';
const DB_USER = process.env.E2E_PG_USER ?? 'banatie_user';
const DB_NAME = process.env.E2E_PG_DB ?? 'banatie_db';

export const queryDb = <T = Record<string, unknown>>(sql: string): T[] => {
  const output = execFileSync(
    'docker',
    ['exec', CONTAINER, 'psql', '-U', DB_USER, '-d', DB_NAME, '--csv', '-c', sql],
    { encoding: 'utf-8' },
  ).trim();

  if (!output) return [];

  const [header, ...rows] = output.split('\n');
  const columns = header.split(',');
  return rows.map((row) => {
    const values = row.split(',');
    return Object.fromEntries(columns.map((col, i) => [col, values[i]])) as T;
  });
};
