import { drizzle } from "drizzle-orm/d1";
import * as schema from "./schema";

type D1Binding = Parameters<typeof drizzle>[0];
type RuntimeBindings = typeof globalThis & {
  __COMPETENCES_PLUS_ENV__?: { DB?: D1Binding };
};

export function getDb() {
  const binding = (globalThis as RuntimeBindings).__COMPETENCES_PLUS_ENV__?.DB;
  if (!binding) {
    throw new Error(
      "Cloudflare D1 binding `DB` is unavailable. Set the `d1` field in .openai/hosting.json to `DB` or let your control plane inject the real binding values before using the database."
    );
  }

  return drizzle(binding, { schema });
}
