import { manage_schema_exports, projects } from "./manage-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/manage/test-manage-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 createTestManageDatabaseClient(drizzleDir) {
	const db = drizzle(new PGlite(), { schema: manage_schema_exports });
	try {
		await migrate(db, { migrationsFolder: drizzleDir });
	} catch (error) {
		console.error("Failed to initialize test database schema:", error);
		throw error;
	}
	return db;
}
function createTestManageDatabaseClientNoMigrations() {
	return drizzle(new PGlite(), { schema: manage_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 cleanupTestManageDatabase(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 closeTestManageDatabase(db) {
	try {
		if ("close" in db && typeof db.close === "function") db.close();
	} catch (error) {
		console.debug("Error closing database:", error);
	}
}
/**
* Creates a test project in the database
* NOTE: original implementation ensured the organization exists first but that is a runtime db entity now
*/
async function createTestProject(db, tenantId, projectId = "default") {
	await db.insert(projects).values({
		tenantId,
		id: projectId,
		name: `Test Project ${projectId}`,
		description: `Test project for ${projectId}`
	}).onConflictDoNothing();
}

//#endregion
export { cleanupTestManageDatabase, closeTestManageDatabase, createTestManageDatabaseClient, createTestManageDatabaseClientNoMigrations, createTestProject };