import dotenv from 'dotenv';
import pg, { type QueryResult, type QueryResultRow } from 'pg';

dotenv.config();

type QueryParams = unknown[] | undefined;

export class DatabaseClient {
  private readonly pool: pg.Pool;

  constructor() {
    const { Pool } = pg;
    this.pool = new Pool({
      host: process.env.POSTGRES_HOST ?? 'localhost',
      port: Number(process.env.POSTGRES_PORT ?? 5432),
      database: process.env.POSTGRES_DB ?? 'flockpal',
      user: process.env.POSTGRES_USER ?? 'flockpal',
      password: process.env.POSTGRES_PASSWORD ?? 'flockpal_dev_password',
    });
  }

  query<T extends QueryResultRow>(text: string, params?: QueryParams): Promise<QueryResult<T>> {
    return this.pool.query<T>(text, params);
  }

  async close() {
    await this.pool.end();
  }
}

export const db = new DatabaseClient();
