import { c as organization } from "./auth-schema.js";
import { A as schema_exports, O as projects } from "./schema.js";
import { dirname, join } from "node:path";
import { sql } from "drizzle-orm";
import { fileURLToPath } from "node:url";
import { PGlite } from "@electric-sql/pglite";
import { drizzle } from "drizzle-orm/pglite";
import { migrate } from "drizzle-orm/pglite/migrator";

//#region src/db/test-client.ts
const DIRNAME = dirname(fileURLToPath(import.meta.url));
/**
* Creates a test database client using an in-memory PostgreSQL database (PGlite)
* This provides real database operations for integration testing with perfect isolation
* Each call creates a fresh database with all migrations applied
*/
async function createTestDatabaseClient(drizzleDir) {
	const db = drizzle(new PGlite(), { schema: schema_exports });
	try {
		if (!drizzleDir) drizzleDir = join(DIRNAME, "../../drizzle");
		await migrate(db, { migrationsFolder: drizzleDir });
	} catch (error) {
		console.error("Failed to initialize test database schema:", error);
		throw error;
	}
	return db;
}
/**
* Cleans up test database by removing all data but keeping schema
* Dynamically gets all tables from the public schema and truncates them
*/
async function cleanupTestDatabase(db) {
	try {
		const tables = (await db.execute(sql.raw(`
      SELECT tablename 
      FROM pg_tables 
      WHERE schemaname = 'public'
    `))).rows.map((row) => row.tablename);
		if (tables.length === 0) return;
		const tableList = tables.map((t) => `"${t}"`).join(", ");
		await db.execute(sql.raw(`TRUNCATE TABLE ${tableList} RESTART IDENTITY CASCADE`));
	} catch (error) {
		console.debug("Could not clean test database:", error);
	}
}
/**
* Closes the test database and removes the file
*/
async function closeTestDatabase(db) {
	try {
		if ("close" in db && typeof db.close === "function") db.close();
	} catch (error) {
		console.debug("Error closing database:", error);
	}
}
/**
* Creates a test organization in the database
* This is a helper for tests that need organization records before creating projects/agents
*/
async function createTestOrganization(db, tenantId) {
	const slug = tenantId.replace(/^test-tenant-/, "").substring(0, 50);
	await db.insert(organization).values({
		id: tenantId,
		name: `Test Organization ${tenantId}`,
		slug,
		createdAt: /* @__PURE__ */ new Date(),
		metadata: null
	}).onConflictDoNothing();
}
/**
* Creates a test project in the database
* Ensures the organization exists first
*/
async function createTestProject(db, tenantId, projectId = "default") {
	await createTestOrganization(db, tenantId);
	await db.insert(projects).values({
		tenantId,
		id: projectId,
		name: `Test Project ${projectId}`,
		description: `Test project for ${projectId}`
	}).onConflictDoNothing();
}

//#endregion
export { createTestProject as a, createTestOrganization as i, closeTestDatabase as n, createTestDatabaseClient as r, cleanupTestDatabase as t };
//# sourceMappingURL=test-client.js.map