// SendGrid API Reference: https://sendgrid.com/docs/api-reference/"
// Errors: https://sendgrid.api-docs.io/v3.0/mail-send/mail-send-errors

profile = "communication/send-email@2.1"
provider = "sendgrid"

map SendEmail {
  INPUTS_MAP = {
    'personalizations.0.to.0.email': 'to',
    'from.email': 'from',
    'subject': 'subject',
  }

  content = []
  attachments = null

  set if (input.text) {
    content = content.concat([{ type: 'text/plain', value: input.text }])
  }

  set if (input.html) {
    content = content.concat([{ type: 'text/html', value: input.html }])
  }

  set if (input.attachments) {
    attachments = input.attachments.map(attachment => {
      return {
        content: attachment.content,
        filename: attachment.filename,
        type: attachment.type,
      }
    })
  }

  http POST "/v3/mail/send" {
    security "bearer_token"
    
    request {
      body = {
        from: { email: input.from },
        subject: input.subject,
        content: content,
        personalizations: [{
          to: [{ email: input.to }], 
        }],
        attachments: attachments,
      }
    }
    
    response 202 "*" {
      map result {
        messageId = headers['x-message-id']
      }
    }

    response 400 "application/json" {
      map error {
        title = "Invalid inputs"
        detail = body.errors.map((err) => `Input '${INPUTS_MAP[err.field] || err.field}': ${err.message}`).join(' ')
      }
    }

    response 413 "application/json" {
      map error {
        title = "Payload Too Large"
        detail = body.errors.map((err) => err.message).join(' ')
      }
    }

    response 401 "application/json" {
      map error {
        title = "Unauthorized"
        detail = body.errors.map((err) => err.message).join(' ')
      }
    }

    response 403 "application/json" {
      map error {
        title = "Forbidden"
        detail = body.errors.map((err) => err.message).join(' ')
      }
    }

    response 500 "application/json" {
      map error {
        title = "Internal server Error"
        detail = body.errors.map((err) => err.message).join(' ')
      }
    }
  }
}