import { runtime_schema_exports } from "./runtime-schema.js";
import { env, loadEnvironmentFiles } from "../../env.js";
import { getLogger } from "../../utils/logger.js";
import { tryAttachDatabasePool } from "../../utils/database-pool.js";
import { getDatabaseErrorLogContext } from "../../utils/error.js";
import { createTestRuntimeDatabaseClientNoMigrations } from "./test-runtime-client.js";
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";

//#region src/db/runtime/runtime-client.ts
loadEnvironmentFiles();
const runtimePoolLogger = getLogger("runtime-db-pool");
/**
* Creates a PostgreSQL database client with connection pooling
*/
function createAgentsRunDatabaseClient(config) {
	const connectionString = config?.connectionString || env.INKEEP_AGENTS_RUN_DATABASE_URL;
	if (env.ENVIRONMENT === "test") return createTestRuntimeDatabaseClientNoMigrations();
	if (!connectionString) throw new Error("INKEEP_AGENTS_RUN_DATABASE_URL environment variable is required. Please set it to your PostgreSQL connection string.");
	const pool = new Pool({
		connectionString,
		max: config?.poolSize || Number(env.POSTGRES_POOL_SIZE) || 100,
		keepAlive: true,
		keepAliveInitialDelayMillis: 6e4,
		connectionTimeoutMillis: 1e4,
		idleTimeoutMillis: 3e4
	});
	tryAttachDatabasePool(pool);
	pool.on("error", (err) => {
		runtimePoolLogger.error({
			error: err,
			...getDatabaseErrorLogContext(err)
		}, "Unexpected error on agents runtime database pool");
	});
	return drizzle(pool, {
		schema: runtime_schema_exports,
		logger: config?.logger
	});
}

//#endregion
export { createAgentsRunDatabaseClient };