/**
 * Functionality that involves outlook.
 */

import { MailData } from "../types/addInTypes";
import { Buffer } from "buffer"

/**
 * Retrieves the IDs of all attachments from the current mail item.
 *
 * @returns {string[]} An array of attachment IDs.
 * @throws {Error} If the mail item cannot be retrieved.
 */
export const getAttachmentIds = (): string[] => {
	console.debug('Starting getAttachments()');
	const item = Office.context.mailbox.item;
	if (!item) throw new Error('Unexpected error; Could not get the mail item.');

	const attachments = item.attachments;
	return attachments.map(att => att.id);
};

/**
 * Asynchronously retrieves data from the currently selected Outlook mail item.
 *
 * This function extracts the subject, sender's email address, and the HTML body of the mail.
 * The body is encoded as a base64 string after being URI-encoded.
 *
 * @returns {Promise<MailData>} A promise that resolves to a `MailData` object.
 *
 * @throws {Error} If the mail body cannot be retrieved, the promise is rejected with an error.
 *
 * @remarks
 * - Uses `Office.context.mailbox.item` to access the current mail item.
 * - The mail body is encoded using `encodeURIComponent` and then converted to base64 using `Buffer`.
 * - If the body retrieval fails, an error is logged and the promise is rejected.
 */
export const getMailData = async(): Promise<MailData> => {
	return new Promise((resolve, reject) => {
		try {
			const item = Office.context.mailbox.item;
			const mailData:MailData = {
				title: item.subject,
				reporter_email: item.sender.emailAddress,
				description: ''
			};

			item.body.getAsync(Office.CoercionType.Html, (bodyResult) => {
				console.log('Reading item body.');
				if (bodyResult.status != Office.AsyncResultStatus.Succeeded){
					reject(
						new Error(
							'Could not successfully recover the body of the mail. If this issue persists contact support@businessmap.io'
						)
					);
					return;
				}
					
				
				// In previous addIn version this was done with btoa() but in the JSDOC was explained that
				// the function was legacy and only mantained for compatibility. The good, new way of doing
				// this would be like this:
				mailData.description = Buffer.from(encodeURIComponent(bodyResult.value)).toString('base64');
				resolve(mailData);
			});

		} catch(e:any) {
			console.error(`Error: ${JSON.stringify(e)}`);
			reject(e);
		}
	});
}