/**
* Copyright Super iPaaS Integration LLC, an IBM Company 2024
*/
import AdmZip from 'adm-zip';
import path from 'path';
// import fs from 'fs';
import { showError, showInfo } from '../../helpers/common/message-helper.js';
import { CHECKING_FOR_PROJECT, CHECKING_ROOT_DIRECTORY } from '../../constants/message-constants.js';
import { ASSERTION, COMMA, ENVIRONMENT, TEST, APIM_MODE } from '../../constants/app-constants.js';
import {
	checkForRootDirPermission,
	checkIfAllProjectExists,
	checkIfRootDirExists
} from '../../helpers/apim/root-dir-helper.js';
import { checkAndLoadDependencies } from '../../helpers/apim/build-helper.js';
import {processProjectBuild} from '@apic/studio-build';
import {addValidAssetsToZip} from '../../helpers/common/zip-helper.js';
import {DebugManager} from '../../debug/debug-manager.js';
import { AssetCache } from '../../cache/asset-cache.js';

const excludeKinds: string[] = [
	TEST,
	ENVIRONMENT,
	ASSERTION,
];

const executeBuildProject = async (rootDirPath: string, projectNames: string): Promise<Buffer> => {
	try {

	    AssetCache.getInstance().clear();
	    AssetCache.getInstance().setProjectNames(projectNames);
	    AssetCache.getInstance().setRootDirPath(rootDirPath);
		/* (*) Validate rootDirPath */
		if(DebugManager.getInstance().isDebugEnabled()) {
			showInfo(CHECKING_ROOT_DIRECTORY);
		}
		checkIfRootDirExists(rootDirPath);
		checkForRootDirPermission(rootDirPath);

		/* (*) Validate projectNames */
		if(DebugManager.getInstance().isDebugEnabled()) {
			showInfo(CHECKING_FOR_PROJECT);
		}
		checkIfAllProjectExists(rootDirPath, projectNames);

		/* (*) Iterate and build project archive */
		const zipFile = new AdmZip();
		buildProjects(rootDirPath, projectNames, zipFile);

		/* (*) Check and Load Dependencies */
		checkAndLoadDependencies(rootDirPath, projectNames, zipFile);
	
		/* (*) Save zip file to current directory for debugging */
		const zipBuffer = zipFile.toBuffer();
		// const debugZipPath = path.join(process.cwd(), 'debug-pre-build.zip');
		// fs.writeFileSync(debugZipPath, zipBuffer);
		// showInfo(`Debug: Saved zip file before processing to: ${debugZipPath}`);
	
		const response = await processProjectBuild(zipBuffer, APIM_MODE);
		if(response && response.success && response.data){
			return response.data;
		}
		/* (*) If build failed, throw error */
		showError('Build failed: ' + (response?.errors || 'Unknown error'));
		process.exit(1);
		

	} catch (error: unknown) {
		showError((error as Error).message);
		process.exit(1);
	}

};

const buildProject = (rootDirPath: string, projectName: string, zipFile: AdmZip) => {
	const projectPath = path.join(rootDirPath, projectName);
	const zipProjectPath = projectName;
	addValidAssetsToZip(projectPath, zipProjectPath, zipFile, excludeKinds);
};
const buildProjects = (rootDirPath: string, projectNames: string, zipFile: AdmZip) => {
	const projects = projectNames.split(COMMA);
	for (const projectName of projects) {
		buildProject(rootDirPath, projectName, zipFile);
	}
};

export { executeBuildProject };

