import { Pool } from 'pg';
import { drizzle, type NodePgDatabase } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import * as schema from './schema';
import path from 'path';

let _pool: Pool | null = null;
let _db: NodePgDatabase<typeof schema> | null = null;
let _migrated = false;

function getPool(): Pool {
  if (!_pool) {
    const DATABASE_URL = process.env.DATABASE_URL;
    if (!DATABASE_URL) {
      throw new Error('DATABASE_URL environment variable is not set');
    }
    _pool = new Pool({ connectionString: DATABASE_URL, max: 10 });
  }
  return _pool;
}

function getDb(): NodePgDatabase<typeof schema> {
  if (!_db) {
    _db = drizzle(getPool(), { schema });
  }
  return _db;
}

export async function runMigrations() {
  if (_migrated) return;
  const isBuildTime = process.env.NEXT_PHASE === 'phase-production-build' || process.env.NEXT_PHASE === 'phase-development-build';
  if (isBuildTime) {
    console.log('ℹ️  Skipping migrations during build phase');
    return;
  }
  try {
    await migrate(getDb(), { migrationsFolder: path.join(process.cwd(), 'drizzle') });
    console.log('✅ Database migrations completed');
    _migrated = true;
  } catch (error) {
    console.error('❌ Migration failed:', error);
    throw error;
  }
}

// Lazy proxy: db is accessed as a module export but only connects on first use
export const db = new Proxy({} as NodePgDatabase<typeof schema>, {
  get(_target, prop, receiver) {
    return Reflect.get(getDb(), prop, receiver);
  },
});
