import { loadEnvironmentFiles } from "../../env.js";
import { createAgentsManageDatabaseClient } from "./manage-client.js";
import { sql } from "drizzle-orm";

//#region src/db/manage/dolt-cleanup.ts
loadEnvironmentFiles();
/**
* Get a database client for cleanup operations
* Allows passing a custom client or uses a default one
*/
const getIntegrationTestClient = (db) => {
	if (db) return db;
	return createAgentsManageDatabaseClient({});
};
/**
* Delete all branches matching a prefix pattern
* Used for cleaning up integration test data
*/
const cleanupBranchesByPrefix = async (prefix, db) => {
	const dbClient = getIntegrationTestClient(db);
	try {
		const branches = await dbClient.execute(sql.raw(`SELECT name FROM dolt_branches WHERE name LIKE '${prefix}%'`));
		for (const branch of branches.rows) {
			const branchName = branch.name;
			try {
				await dbClient.execute(sql.raw(` DOLT_BRANCH('-D', '${branchName}')`));
			} catch (error) {
				console.debug(`Could not delete branch ${branchName}:`, error);
			}
		}
	} catch (error) {
		console.error(`Error cleaning up branches with prefix ${prefix}:`, error);
	}
};
/**
* Delete all tags matching a prefix pattern
* Used for cleaning up integration test data
*/
const cleanupTagsByPrefix = async (prefix, db) => {
	const dbClient = getIntegrationTestClient(db);
	try {
		const tags = await dbClient.execute(sql.raw(`SELECT tag_name FROM dolt_tags WHERE tag_name LIKE '${prefix}%'`));
		for (const tag of tags.rows) {
			const tagName = tag.tag_name;
			try {
				await dbClient.execute(sql.raw(`SELECT DOLT_TAG('-d', '${tagName}')`));
			} catch (error) {
				console.debug(`Could not delete tag ${tagName}:`, error);
			}
		}
	} catch (error) {
		console.error(`Error cleaning up tags with prefix ${prefix}:`, error);
	}
};
/**
* Delete specific branches by name
* Used for cleaning up integration test data
*/
const cleanupBranches = async (branchNames, db) => {
	const dbClient = getIntegrationTestClient(db);
	for (const branchName of branchNames) try {
		await dbClient.execute(sql.raw(`SELECT DOLT_BRANCH('-D', '${branchName}')`));
	} catch (error) {
		console.debug(`Could not delete branch ${branchName}:`, error);
	}
};
/**
* Delete specific tags by name
* Used for cleaning up integration test data
*/
const cleanupTags = async (tagNames, db) => {
	const dbClient = getIntegrationTestClient(db);
	for (const tagName of tagNames) try {
		await dbClient.execute(sql.raw(`SELECT DOLT_TAG('-d', '${tagName}')`));
	} catch (error) {
		console.debug(`Could not delete tag ${tagName}:`, error);
	}
};
/**
* Comprehensive cleanup for test data by prefix
* Used for cleaning up integration test data
*/
const cleanupTestData = async (prefix, branches, tags, db) => {
	if (tags && tags.size > 0) await cleanupTags(tags, db);
	await cleanupTagsByPrefix(prefix, db);
	if (branches && branches.size > 0) await cleanupBranches(branches, db);
	await cleanupBranchesByPrefix(prefix, db);
};
/**
* Delete all branches matching a tenant prefix
* Used for cleaning up integration test data
*/
const cleanupTenantBranches = async (tenantId, db) => {
	const dbClient = getIntegrationTestClient(db);
	try {
		const pattern = `${tenantId}_%`;
		const branches = await dbClient.execute(sql.raw(`SELECT name FROM dolt_branches WHERE name LIKE '${pattern}'`));
		for (const branch of branches.rows) {
			const branchName = branch.name;
			try {
				await dbClient.execute(sql.raw(`SELECT DOLT_BRANCH('-D', '${branchName}')`));
			} catch (error) {
				console.debug(`Could not delete branch ${branchName}:`, error);
			}
		}
	} catch (error) {
		console.error(`Error cleaning up branches for tenant ${tenantId}:`, error);
	}
};
/**
* Comprehensive cleanup for a tenant: deletes tags and branches
* Used for cleaning up integration test data
*/
const cleanupTenant = async (tenantId, tagNames, db) => {
	try {
		if (tagNames && tagNames.size > 0) await cleanupTags(tagNames, db);
		await cleanupTenantBranches(tenantId, db);
	} catch (error) {
		console.error(`Error cleaning up tenant ${tenantId}:`, error);
	}
};
/**
* Cleanup multiple tenants
* Used for cleaning up integration test data
*/
const cleanupTenants = async (tenantIds, tagNames, db) => {
	if (tagNames && tagNames.size > 0) await cleanupTags(tagNames, db);
	for (const tenantId of tenantIds) await cleanupTenantBranches(tenantId, db);
};

//#endregion
export { cleanupBranches, cleanupBranchesByPrefix, cleanupTags, cleanupTagsByPrefix, cleanupTenant, cleanupTenantBranches, cleanupTenants, cleanupTestData, getIntegrationTestClient };