/**
* Copyright Super iPaaS Integration LLC, an IBM Company 2024
*/
import AdmZip from 'adm-zip';
import path from 'path';
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 } 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';

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

const executeBuildProject = async (rootDirPath: string, projectNames: string): Promise<Buffer> => {
	try {
		/* (*) 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);

		/* (*) Invoke Studio Build API */
		const zipBuffer = await processProjectBuild(zipFile.toBuffer());
		/* (*)return the zip file */
		return zipBuffer;

	} 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 };

