var Azure = {
	params: {},
	token: null,

	setParams: function (params) {
		['app_id', 'password', 'tenant_id', 'subscription_id', 'resource_id', 'period'].forEach(function (field) {
			if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
				throw 'Required param is not set: ' + field + '.';
			}
		});

		Azure.params = params;
	},

	login: function () {
		var response, login = new HttpRequest();

		if (typeof Azure.params.proxy !== 'undefined' && Azure.params.proxy !== '') {
			login.setProxy(Azure.params.proxy);
		}

		login.addHeader('Content-Type: application/x-www-form-urlencoded');
		response = login.post(
			'https://login.microsoftonline.com/' + encodeURIComponent(Azure.params.tenant_id) + '/oauth2/token',
			'grant_type=client_credentials&resource=' + encodeURIComponent('https://management.azure.com/') + '&client_id=' + encodeURIComponent(Azure.params.app_id) + '&client_secret=' + encodeURIComponent(Azure.params.password)
		);

		if (login.getStatus() !== 200) {
			throw 'Login failed with status code ' + login.getStatus() + ': ' + response;
		}

		try {
			response = JSON.parse(response);
		}
		catch (error) {
			throw 'Failed to parse login session response.';
		}

		if (!response.hasOwnProperty('access_token')) {
			throw 'Authentication response does not contain access token.';
		}

		Azure.token = response['access_token'];
	},

	request: function (url) {
		var response, request = new HttpRequest();

		if (typeof Azure.params.proxy !== 'undefined' && Azure.params.proxy !== '') {
			request.setProxy(Azure.params.proxy);
		}

		if (!Azure.token) {
			throw 'Request does not contain access token.';
		}

		request.addHeader('Content-Type: application/json');
		request.addHeader('Authorization: Bearer ' + Azure.token);
		Zabbix.log(4, '[ Azure Vault ] request url: ' + url);

		response = request.get(url);

		if (request.getStatus() !== 200) {
			throw 'Request failed with status code ' + request.getStatus() + ': ' + response;
		}

		try {
			return JSON.parse(response);
		}
		catch (error) {
			throw 'Failed to parse response received from API.';
		}
	},

	getField: function (data, path) {
		var steps = path.split('.');

		for (var i = 0; i < steps.length; i++) {
			var step = steps[i];
			if (typeof data !== 'object' || typeof data[step] === 'undefined') {
				throw 'Required field was not found: ' + path;
			}
			data = data[step];
		}

		return data;
	},

	getMetricsData: function () {
		var data = {},
			end_date = new Date(),
			start_date = new Date();

		function formatDate(date) {
			var year = date.getFullYear(),
				month = (date.getMonth() + 1),
				day = date.getDate(),
				hours = date.getHours(),
				minutes = date.getMinutes(),
				seconds = date.getSeconds(),
				ampm = hours >= 12 ? 'PM' : 'AM';

			hours = hours % 12 || 12;
			month = month < 10 ? '0' + month : month;
			day = day < 10 ? '0' + day : day;
			hours = hours < 10 ? '0' + hours : hours;
			minutes = minutes < 10 ? '0' + minutes : minutes;
			seconds = seconds < 10 ? '0' + seconds : seconds;

			formatted_date = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds + ' ' + ampm;

			return formatted_date
		};

		start_date.setDate(start_date.getDate() - Azure.params.period);
		end_date = encodeURIComponent('\\'' + formatDate(end_date) + '\\'');
		start_date = encodeURIComponent('\\'' + formatDate(start_date) + '\\'');
		date_filter = '&$filter=' + encodeURIComponent('startTime eq ') + start_date + encodeURIComponent(' and endTime eq ') + end_date;

		data.health = Azure.getField(Azure.request('https://management.azure.com' + Azure.params.resource_id + '/providers/Microsoft.ResourceHealth/availabilityStatuses?api-version=2020-05-01'), 'value.0.properties');
		data.jobs = Azure.getField(Azure.request('https://management.azure.com' + Azure.params.resource_id + '/backupjobs?api-version=2025-01-01' + date_filter), 'value');

		return data
	}
};

try {
	Azure.setParams(JSON.parse(value));
	Azure.login();
	return JSON.stringify(Azure.getMetricsData());
}
catch (error) {
	error += (String(error).endsWith('.')) ? '' : '.';
	Zabbix.log(3, '[ Azure Vault ] ERROR: ' + error);
	return JSON.stringify({ 'error': error });
}