import { organization } from "../../auth/auth-schema.js";
import { runtime_schema_exports } from "./runtime-schema.js";
import { sql } from "drizzle-orm";
import { PGlite } from "@electric-sql/pglite";
import { drizzle } from "drizzle-orm/pglite";
import { migrate } from "drizzle-orm/pglite/migrator";

//#region src/db/runtime/test-runtime-client.ts
/**
* 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 createTestRuntimeDatabaseClient(drizzleDir) {
	const db = drizzle(new PGlite(), { schema: runtime_schema_exports });
	try {
		await migrate(db, { migrationsFolder: drizzleDir });
	} catch (error) {
		console.error("Failed to initialize test database schema:", error);
		throw error;
	}
	return db;
}
function createTestRuntimeDatabaseClientNoMigrations() {
	return drizzle(new PGlite(), { schema: runtime_schema_exports });
}
/**
* Cleans up test database by removing all data but keeping schema
* Dynamically gets all tables from the public schema and truncates them
*/
async function cleanupTestRuntimeDatabase(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 closeTestRuntimeDatabase(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-/, "");
	await db.insert(organization).values({
		id: tenantId,
		name: `Test Organization ${tenantId}`,
		slug,
		createdAt: /* @__PURE__ */ new Date(),
		metadata: null
	}).onConflictDoNothing();
}

//#endregion
export { cleanupTestRuntimeDatabase, closeTestRuntimeDatabase, createTestOrganization, createTestRuntimeDatabaseClient, createTestRuntimeDatabaseClientNoMigrations };