/**
* Copyright Super iPaaS Integration LLC, an IBM Company 2024
*/
import axios from 'axios';
import FormData from 'form-data';
import { GatewaysJson } from '@apic/studio-shared';
import { AppConstants } from '../constants/app-constants.js';
import { LogWrapper } from './log-wrapper.js';

export const sendToGateway = async (
	gatewayURL: string,
	gatewayUser: string,
	gatewaySecret: string,
	is_mcsp_enabled: boolean,
	zipBuffer: Buffer,
	gatewaysJsonContent: GatewaysJson
) => {
	const formData = new FormData();
	formData.append('file', zipBuffer, 'gatewayInstance.zip');
	formData.append('overwrite', gatewaysJsonContent.overwrite);

	let authorizationHeader ;

	if(is_mcsp_enabled)
	{
		authorizationHeader = `Bearer ${gatewaySecret}`;
	}
	else{
		const credentials = `${gatewayUser}:${gatewaySecret}`;
		const encodedCredentials = Buffer.from(credentials).toString('base64');
		authorizationHeader = `Basic ${encodedCredentials}`;
	}

	LogWrapper.logDebug('0108', gatewayURL);

	return axios.post(gatewayURL + AppConstants.DEPLOY_GATEWAY_URL, formData, {
		headers: {
			...formData.getHeaders(),
			'Authorization': authorizationHeader,
		},
	}).then((response) => {
		LogWrapper.logDebug('0010', JSON.stringify(response.data));
		return {
			error: false,
			statusCode: response.status,
			data: response.data,
		};
	}).catch((error) => {
		const errorMessage = `Error sending to ${gatewayURL}: ${error.message}`;
		LogWrapper.logError('0009', 'Deployment', errorMessage);

		return {
			error: true,
			statusCode: error.response ? error.response.status : 404,
			data: error.response ? error.response.data : null,
		};
	});
};


export async function validationManager(url: string, authorizationHeader: string) {
	LogWrapper.logDebug('0253', url);
	return axios
		.get(url, {
			timeout: 20000,
			headers: {
				'Authorization': authorizationHeader,
			}
		})
		.then(res => {
			LogWrapper.logDebug('0009', res.data as string);
			if (res.status === 200) {
				return { data: 'OK', status: 200 };
			} else {
				LogWrapper.logWarn('0008', 'Validation', `Unexpected status code: ${res.status}`);
				throw new Error(JSON.stringify({ message: { data: res.data, status: res.status } }));
			}
		})
		.catch((err) => {
			if (err.response) {
				const status = err.response.status;
				const errorData = err.response.data;
				if (status === 401) {
					LogWrapper.logError('0008', 'Authorization', 'The user name or password did not match.');
					throw new Error(JSON.stringify({ message: { data: 'The user name or password did not match.', status: 401 } }));
				} else if (status === 502) {
					LogWrapper.logError('0008', 'Validation', 'Bad Gateway.');
					throw new Error(JSON.stringify({ message: { data: 'Bad Gateway', status: 502 } }));
				} else if (status === 404) {
					LogWrapper.logError('0008', 'Validation', 'Gateway not found.');
					throw new Error(JSON.stringify({ message: { data: 'Gateway not found', status: 404 } }));
				} else {
					LogWrapper.logError('0008', 'Validation', `Status: ${status} Data: ${errorData}`);
					throw new Error(JSON.stringify({ message: { data: errorData, status: status } }));
				}
			} else if (err.code === 'ECONNABORTED') {
				LogWrapper.logError('0008', 'Validation', 'Request timed out.');
				throw new Error(JSON.stringify({ message: { data: 'Gateway not found', status: 404 } }));
			} else {
				LogWrapper.logError('0008', 'Validation', err.message);
				throw new Error(JSON.stringify({ message: { data: 'Something went wrong while validating the gateway.', status: 500 } }));
			}
		});
}




