module.exports = {
  friendlyName: 'Send email via Mailjet',

  inputs: {
    to: {
      type: 'string',
      required: true
    },
    subject: {
      type: 'string',
      required: true
    },
    html: {
      type: 'string',
      required: true
    },
    nameDestinataire: {
            type: 'string',
            //required: true
        },
  },

  exits: {
    success: {
      description: 'Email sent successfully'
    },
    error: {
      description: 'Failed to send email'
    }
  },

  fn: async function ({ to, subject, html, nameDestinataire }, exits) {
    try {
    
         const Mailjet = require('node-mailjet');

      const mailjet = Mailjet.apiConnect(
        sails.config.externalApis.mailjet.apiKey,
        sails.config.externalApis.mailjet.apiSecret
      );

      const request = await mailjet
        .post('send', { version: 'v3.1' })
        .request({
          Messages: [
            {
              From: {
                Email: sails.config.externalApis.mailjet.senderEmail,
                Name: sails.config.externalApis.mailjet.senderName
              },
              To: [{ Email: to, Name: `${nameDestinataire}` }],
              Subject: subject,
              HTMLPart: html
            }
          ]
        });

      sails.log.info('Email sent to', to, 'with status', request.response.status);
      return exits.success();
    } catch (err) {
      sails.log.error('Mailjet error:', err);
      return exits.error(err);
    }
  }
};