import { drizzle as drizzleNeon } from 'drizzle-orm/neon-serverless';
import { drizzle as drizzleNode } from 'drizzle-orm/node-postgres';
import { Pool as NeonPool, neonConfig } from '@neondatabase/serverless';
import pg from 'pg';
import type { Pool as PgPoolType } from 'pg';
import ws from "ws";
import * as schema from "@shared/schema";

const { Pool: PgPool } = pg;

if (!process.env.DATABASE_URL) {
  throw new Error(
    "DATABASE_URL must be set. Did you forget to provision a database?",
  );
}

// Check if running on Replit (Neon) or AlmaLinux (PostgreSQL)
const isNeon = process.env.DATABASE_URL.includes('neon.tech') || 
               process.env.DATABASE_URL.includes('neon.aws');

let pool: NeonPool | PgPoolType;
let db: ReturnType<typeof drizzleNeon> | ReturnType<typeof drizzleNode>;

if (isNeon) {
  // Neon serverless (Replit)
  neonConfig.webSocketConstructor = ws;
  pool = new NeonPool({ connectionString: process.env.DATABASE_URL });
  db = drizzleNeon(pool, { schema });
  console.log('📦 Using Neon serverless database');
} else {
  // PostgreSQL standard (AlmaLinux)
  pool = new PgPool({ connectionString: process.env.DATABASE_URL });
  db = drizzleNode(pool, { schema });
  console.log('🐘 Using standard PostgreSQL database');
}

// Health check: test database connection on startup
pool.query('SELECT 1')
  .then(() => console.log('✅ Database connection successful'))
  .catch((err) => {
    console.error('❌ Database connection failed:', err.message);
    // Mask entire connection string for security
    const dbType = isNeon ? 'Neon Cloud' : 'PostgreSQL';
    console.error(`Database type: ${dbType}`);
  });

export { pool, db };
