/**
 * Database Connection Setup
 * Exports configured Drizzle instance
 */

import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';

// Global connection instance
let connectionString: string | undefined;
let client: postgres.Sql | undefined;
let dbInstance: ReturnType<typeof drizzle> | undefined;

/**
 * Initialize database connection
 * @param url PostgreSQL connection string
 */
export function initializeDatabase(url: string) {
  if (dbInstance) {
    throw new Error('Database already initialized');
  }

  connectionString = url;
  client = postgres(url);
  dbInstance = drizzle(client, { schema });

  return dbInstance;
}

/**
 * Get database instance
 * Throws if not initialized
 */
export function getDatabase() {
  if (!dbInstance) {
    throw new Error('Database not initialized. Call initializeDatabase() first.');
  }
  return dbInstance;
}

/**
 * Close database connection
 */
export async function closeDatabase() {
  if (client) {
    await client.end();
    client = undefined;
    dbInstance = undefined;
  }
}

/**
 * Export the database instance for direct import
 * Note: This will throw if accessed before initialization
 */
export const db = new Proxy({} as ReturnType<typeof drizzle>, {
  get(target, prop) {
    const instance = getDatabase();
    return (instance as any)[prop];
  },
});

export type Database = typeof db;
