import type { D1Database } from '@cloudflare/workers-types'
import { drizzle, type DrizzleD1Database } from 'drizzle-orm/d1'
import * as schema from './schema'

type DbClient = DrizzleD1Database<typeof schema>

let dbInstance: DbClient | null = null

export function initDb(database: D1Database): void {
  const base = drizzle(database, { schema }) as DbClient
  dbInstance = Object.assign(base, {
    transaction: async <T>(handler: (tx: DbClient) => Promise<T>): Promise<T> => {
      return handler(base)
    },
  })
}

export const db = new Proxy({} as DbClient, {
  get(_target, prop: keyof DbClient) {
    if (!dbInstance) {
      throw new Error('D1 database not initialized. Call initDb(env.DB) before using db helpers.')
    }

    return dbInstance[prop]
  },
})
