import { Injectable, OnModuleDestroy } from '@nestjs/common';
import { Pool, QueryResultRow } from 'pg';

@Injectable()
export class DatabaseService implements OnModuleDestroy {
  private readonly pool: Pool | null;

  constructor() {
    const connectionString = process.env.DATABASE_URL?.trim();
    this.pool = connectionString
      ? new Pool({
          connectionString,
          max: Number(process.env.DB_POOL_MAX || 5),
          idleTimeoutMillis: 30_000,
          connectionTimeoutMillis: 8_000,
          ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: process.env.DB_SSL_REJECT_UNAUTHORIZED !== 'false' } : undefined
        })
      : null;
  }

  isConfigured() {
    return Boolean(this.pool);
  }

  async query<T extends QueryResultRow = QueryResultRow>(text: string, values: unknown[] = []) {
    if (!this.pool) throw new Error('DATABASE_NOT_CONFIGURED');
    return this.pool.query<T>(text, values);
  }

  async ping() {
    if (!this.pool) return { configured: false, ok: false, code: 'DATABASE_NOT_CONFIGURED' };
    const started = Date.now();
    try {
      await this.pool.query('SELECT 1');
      return { configured: true, ok: true, latencyMs: Date.now() - started };
    } catch {
      return { configured: true, ok: false, code: 'DATABASE_UNREACHABLE', latencyMs: Date.now() - started };
    }
  }

  async onModuleDestroy() {
    await this.pool?.end();
  }
}
