import { drizzle } from 'drizzle-orm/node-postgres';
import pkg from 'pg';
const { Pool } = pkg;
import * as schema from '../db/schema.js';

// PostgreSQL connection pool
const pool = new Pool({
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT || '5432'),
  user: process.env.DB_USER || 'admin',
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME || 'crm',
  max: 20, // maximum number of connections in pool
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});

// Critical database errors - use console.error directly to avoid circular imports
pool.on('error', (err) => {
  console.error('[FATAL] Database connection error:', err.message);
  process.exit(-1);
});

// Initialize Drizzle ORM with schema
export const db = drizzle(pool, { schema });

// Test database connection
export const testConnection = async () => {
  const client = await pool.connect();
  client.release();
  return true;
};

// Export pool for direct access if needed
export { pool };
