import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import * as schema from './schema.js'

export type Db = PostgresJsDatabase<typeof schema>

export interface DbHandle {
  db: Db
  close: () => Promise<void>
}

export function createDb(url: string, opts: { max?: number; applicationName?: string } = {}): DbHandle {
  const client = postgres(url, {
    max: opts.max ?? 10,
    connection: { application_name: opts.applicationName ?? 'mcp-znet' },
    onnotice: () => {},
  })
  return { db: drizzle(client, { schema }), close: () => client.end({ timeout: 5 }) }
}
