import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import { tables as layerTables } from '../database/schema/index'

// Export commonly used query builder functions
export { eq, and, or, ne, not, lt, gt, asc, desc, count } from 'drizzle-orm'
export { sql } from 'drizzle-orm'

// Build schema by allowing extending apps to register additional tables at runtime
type TablesDictionary = Record<string, unknown>

export const tables: TablesDictionary = { ...layerTables }

export function registerTables(extraTables: TablesDictionary) {
  if (extraTables && typeof extraTables === 'object') {
    Object.assign(tables, extraTables)
  }
}

// Create a singleton connection with proper pooling
let db: ReturnType<typeof drizzle> | null = null
let client: ReturnType<typeof postgres> | null = null

export function useDB() {
  const config = useRuntimeConfig()

  if (!config.databaseUrl) {
    throw new Error('Database URL not configured')
  }

  if (!db) {
    // Create postgres client with connection pooling
    client = postgres(config.databaseUrl, {
      max: 10, // Maximum number of connections in the pool
      idle_timeout: 20, // Close idle connections after 20 seconds
      max_lifetime: 60 * 30, // Close connections after 30 minutes
      connect_timeout: 10, // 10 second connection timeout
      onnotice: () => {} // Suppress NOTICE messages
    })

    db = drizzle(client, { schema: tables })
  }

  return db
}

// Close database connections when process exits
if (import.meta.prerender) {
  // During static generation, close connections after prerendering
  process.on('beforeExit', async () => {
    if (client) {
      await client.end({ timeout: 5 })
      client = null
      db = null
    }
  })
}
