import fs from 'fs';
import path from 'path';
import auth from '../../../../Auth.js';
import { globalOptionsZod } from '../../../../Command.js';
import request from '../../../../request.js';
import { accessToken } from '../../../../utils/accessToken.js';
import { formatting } from '../../../../utils/formatting.js';
import GraphCommand from '../../../base/GraphCommand.js';
import commands from '../../commands.js';
import { z } from 'zod';
export const options = z.strictObject({
    ...globalOptionsZod.shape,
    subject: z.string().alias('s'),
    to: z.string().alias('t'),
    cc: z.string().optional(),
    bcc: z.string().optional(),
    sender: z.string().optional(),
    mailbox: z.string().optional().alias('m'),
    bodyContents: z.string(),
    bodyContentType: z.enum(['Text', 'HTML']).optional(),
    importance: z.enum(['low', 'normal', 'high']).optional(),
    attachment: z.union([z.string(), z.string().array()]).optional(),
    saveToSentItems: z.boolean().optional()
});
class OutlookMailSendCommand extends GraphCommand {
    get name() {
        return commands.MAIL_SEND;
    }
    get description() {
        return 'Sends an email';
    }
    get schema() {
        return options;
    }
    getRefinedSchema(schema) {
        return schema
            .refine(options => {
            if (!options.attachment) {
                return true;
            }
            const attachments = typeof options.attachment === 'string' ? [options.attachment] : options.attachment;
            for (const attachment of attachments) {
                if (!fs.existsSync(attachment)) {
                    return false;
                }
                if (!fs.lstatSync(attachment).isFile()) {
                    return false;
                }
            }
            const requestBody = this.getRequestBody(options);
            // The max body size of the request is 4 194 304 chars before getting a 413 response
            if (JSON.stringify(requestBody).length > 4194304) {
                return false;
            }
            return true;
        }, {
            error: (ctx) => {
                const opts = ctx.input;
                const attachments = typeof opts.attachment === 'string' ? [opts.attachment] : opts.attachment;
                for (const attachment of attachments) {
                    if (!fs.existsSync(attachment)) {
                        return `File with path '${attachment}' was not found.`;
                    }
                    if (!fs.lstatSync(attachment).isFile()) {
                        return `'${attachment}' is not a file.`;
                    }
                }
                return 'Exceeded the max total size of attachments which is 3MB.';
            }
        });
    }
    async commandAction(logger, args) {
        try {
            const isAppOnlyAccessToken = accessToken.isAppOnlyAccessToken(auth.connection.accessTokens[this.resource].accessToken);
            if (isAppOnlyAccessToken === true && !args.options.sender) {
                throw `Specify a upn or user id in the 'sender' option when using app only authentication.`;
            }
            const requestOptions = {
                url: `${this.resource}/v1.0/${args.options.sender ? 'users/' + formatting.encodeQueryParameter(args.options.sender) : 'me'}/sendMail`,
                headers: {
                    accept: 'application/json;odata.metadata=none',
                    'content-type': 'application/json'
                },
                responseType: 'json',
                data: this.getRequestBody(args.options)
            };
            await request.post(requestOptions);
        }
        catch (err) {
            this.handleRejectedODataJsonPromise(err);
        }
    }
    mapEmailAddressToRecipient(email) {
        if (!email) {
            return undefined;
        }
        return {
            emailAddress: {
                address: email.trim()
            }
        };
    }
    getRequestBody(options) {
        const attachments = typeof options.attachment === 'string' ? [options.attachment] : options.attachment;
        const attachmentContents = attachments?.map(a => ({
            '@odata.type': '#microsoft.graph.fileAttachment',
            name: path.basename(a),
            contentBytes: fs.readFileSync(a, { encoding: 'base64' })
        }));
        return ({
            message: {
                subject: options.subject,
                body: {
                    contentType: options.bodyContentType || 'Text',
                    content: options.bodyContents
                },
                from: this.mapEmailAddressToRecipient(options.mailbox),
                toRecipients: options.to.split(',').map(mail => this.mapEmailAddressToRecipient(mail)),
                ccRecipients: options.cc?.split(',').map(mail => this.mapEmailAddressToRecipient(mail)),
                bccRecipients: options.bcc?.split(',').map(mail => this.mapEmailAddressToRecipient(mail)),
                importance: options.importance,
                attachments: attachmentContents
            },
            saveToSentItems: options.saveToSentItems
        });
    }
}
export default new OutlookMailSendCommand();
//# sourceMappingURL=mail-send.js.map