"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
let cachedAssets = null;
async function loadPGliteAssets() {
  if (cachedAssets) return cachedAssets;
  const base = "/";
  const [wasmResp, dataResp] = await Promise.all([
    fetch(`${base}pglite.wasm`),
    fetch(`${base}pglite.data`)
  ]);
  const [wasmModule, fsBundle] = await Promise.all([
    WebAssembly.compileStreaming(wasmResp),
    dataResp.blob()
  ]);
  cachedAssets = { wasmModule, fsBundle };
  return cachedAssets;
}
const instances = /* @__PURE__ */ new Map();
function instanceKey(name, namespace) {
  return namespace && namespace !== "global" ? `${namespace}::${name}` : name;
}
async function initPGliteInstance(name, schemaSQL, idbPath, namespace) {
  const key = instanceKey(name, namespace);
  if (instances.has(key)) {
    await closePGliteInstance(name, namespace);
  }
  const { PGlite: PGliteClass } = await Promise.resolve().then(() => require("./index-skt9-lu6.cjs")).then((n) => n.index);
  const { wasmModule, fsBundle } = await loadPGliteAssets();
  const db = idbPath ? new PGliteClass(idbPath, { wasmModule, fsBundle }) : new PGliteClass({ wasmModule, fsBundle });
  instances.set(key, db);
  if (schemaSQL) {
    await db.exec(schemaSQL);
    console.log(`[pglite] Schema applied for "${name}"`);
  }
}
async function closePGliteInstance(name, namespace) {
  const key = instanceKey(name, namespace);
  const db = instances.get(key);
  if (db) {
    await db.close();
    instances.delete(key);
  }
}
async function closeAllPGlite() {
  const keys = [...instances.keys()];
  await Promise.all(
    keys.map(async (key) => {
      const db = instances.get(key);
      if (db) {
        await db.close();
        instances.delete(key);
      }
    })
  );
}
function getInstanceNames() {
  return [...instances.keys()];
}
function getInstance(name, namespace) {
  return instances.get(instanceKey(name, namespace));
}
async function applyPendingMigrations(vfs, dbName, namespace) {
  const db = instances.get(instanceKey(dbName, namespace));
  if (!db) return { applied: [], errors: ["Database not initialized"] };
  await db.exec(`CREATE TABLE IF NOT EXISTS _drizzle_migrations (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL UNIQUE,
    applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
  )`);
  const appliedResult = await db.query("SELECT name FROM _drizzle_migrations ORDER BY name");
  const appliedSet = new Set(appliedResult.rows.map((r) => r.name));
  let files;
  try {
    files = vfs.readdirSync("/project/drizzle").filter((f) => f.endsWith(".sql")).sort();
  } catch {
    return { applied: [], errors: [] };
  }
  const pending = files.filter((f) => !appliedSet.has(f));
  const applied = [];
  const errors = [];
  for (const file of pending) {
    try {
      const raw = vfs.readFileSync(`/project/drizzle/${file}`);
      const sql = typeof raw === "string" ? raw : new TextDecoder().decode(raw);
      await db.exec(sql);
      await db.exec(`INSERT INTO _drizzle_migrations (name) VALUES ('${file}')`);
      applied.push(file);
    } catch (e) {
      errors.push(`${file}: ${e.message || String(e)}`);
      break;
    }
  }
  return { applied, errors };
}
async function initAndMigrate(name, vfs, idbPath, namespace) {
  await initPGliteInstance(name, null, idbPath, namespace);
  const hasDrizzleDir = (() => {
    try {
      const stat = vfs.statSync("/project/drizzle");
      return stat.isDirectory();
    } catch {
      return false;
    }
  })();
  if (hasDrizzleDir) {
    const { applied, errors } = await applyPendingMigrations(vfs, name, namespace);
    if (applied.length > 0) {
      console.log(`[pglite] Applied ${applied.length} migration(s) for "${name}"`);
    }
    if (errors.length > 0) {
      console.error(`[pglite] Migration errors for "${name}":`, errors);
    }
    return;
  }
  try {
    const raw = vfs.readFileSync("/project/schema.sql");
    const schemaSQL = typeof raw === "string" ? raw : new TextDecoder().decode(raw);
    const db = instances.get(instanceKey(name, namespace));
    if (db && schemaSQL) {
      await db.exec(schemaSQL);
      console.log(`[pglite] Schema applied for "${name}" (legacy schema.sql)`);
    }
  } catch {
  }
}
async function handleDatabaseRequest(operation, body, dbName, namespace) {
  let db;
  if (namespace !== void 0) {
    const { getActiveDatabase } = await Promise.resolve().then(() => require("./db-manager-DokKoikG.cjs"));
    const name = dbName || getActiveDatabase(namespace) || void 0;
    db = name ? instances.get(instanceKey(name, namespace)) : void 0;
  } else {
    const name = dbName || instances.keys().next().value;
    db = name ? instances.get(name) : void 0;
  }
  if (!db) {
    return {
      statusCode: 503,
      body: JSON.stringify({ error: `PGlite not initialized${dbName ? ` for "${dbName}"` : ""}` })
    };
  }
  try {
    switch (operation) {
      case "query": {
        const { sql, params } = body;
        if (!sql) {
          return { statusCode: 400, body: JSON.stringify({ error: "Missing sql parameter" }) };
        }
        const result = await db.query(sql, params || []);
        return {
          statusCode: 200,
          body: JSON.stringify({ rows: result.rows, fields: result.fields })
        };
      }
      case "exec": {
        const { sql } = body;
        if (!sql) {
          return { statusCode: 400, body: JSON.stringify({ error: "Missing sql parameter" }) };
        }
        await db.exec(sql);
        return {
          statusCode: 200,
          body: JSON.stringify({ success: true })
        };
      }
      case "tables": {
        const result = await db.query(`
          SELECT table_name FROM information_schema.tables
          WHERE table_schema = 'public'
          ORDER BY table_name
        `);
        return {
          statusCode: 200,
          body: JSON.stringify({ tables: result.rows.map((r) => r.table_name) })
        };
      }
      default: {
        if (operation.startsWith("schema/")) {
          const table = operation.slice(7);
          if (!table) {
            return { statusCode: 400, body: JSON.stringify({ error: "Missing table name" }) };
          }
          const result = await db.query(`
            SELECT column_name, data_type, is_nullable, column_default
            FROM information_schema.columns
            WHERE table_schema = 'public' AND table_name = $1
            ORDER BY ordinal_position
          `, [table]);
          return {
            statusCode: 200,
            body: JSON.stringify({ table, columns: result.rows })
          };
        }
        return {
          statusCode: 404,
          body: JSON.stringify({ error: `Unknown operation: ${operation}` })
        };
      }
    }
  } catch (err) {
    console.error(`[pglite] ${operation} error:`, err);
    return {
      statusCode: 500,
      body: JSON.stringify({ error: err.message || String(err) })
    };
  }
}
exports.applyPendingMigrations = applyPendingMigrations;
exports.closeAllPGlite = closeAllPGlite;
exports.closePGliteInstance = closePGliteInstance;
exports.getInstance = getInstance;
exports.getInstanceNames = getInstanceNames;
exports.handleDatabaseRequest = handleDatabaseRequest;
exports.initAndMigrate = initAndMigrate;
exports.initPGliteInstance = initPGliteInstance;
exports.loadPGliteAssets = loadPGliteAssets;
//# sourceMappingURL=pglite-database-B_9oIeFO.cjs.map
