//! SendGrid integration for [Flows.network](https://flows.network)
//!
//! # Quick Start
//!
//! To get started, let's write a very tiny flow function.
//!
//! ```rust
//! use openai_flows::{Email, send_email};
//! use slack_flows::{listen_to_channel};
//!
//! #[no_mangle]
//! pub fn run() {
//!     listen_to_channel("myworkspace", "mychannel", |sm| {
//!         let email = Email {
//!             to: vec!["receiver@domain.com"],
//!             subject: "Hi",
//!             content: sm.text
//!         };
//!         send_email("sender@domain.com", email);
//!     });
//! }
//! ```
//!
//! When the Slack message is received, send email using [send_email].

use http_req::{
    request::{Method, Request},
    uri::Uri,
};
use lazy_static::lazy_static;
use serde::Serialize;
use urlencoding::encode;

lazy_static! {
    static ref SENDGRID_API_PREFIX: String = String::from(
        std::option_env!("SENDGRID_API_PREFIX")
            .unwrap_or("https://sendgrid-flows-integration.vercel.app/api")
    );
}

extern "C" {
    fn get_flows_user(p: *mut u8) -> i32;
    fn set_error_log(p: *const u8, len: i32);
}

/// Struct for the email.
///
#[derive(Debug, Serialize)]
pub struct Email {
    pub to: Vec<String>,
    pub subject: String,
    pub content: String,
}

/// Send email with provided email parameter.
///
/// `sender` is the sender's email when you connect
/// [Flows.network](https://flows.network) platform with your SendGrid account.
///
/// `email` is a [Email] object.
///
/// If you have not connected your SendGrid account with [Flows.network platform](https://flows.network),
/// you will receive an error in the flow's running log.
///
pub fn send_email(sender: &str, email: &Email) -> Result<(), String> {
    unsafe {
        let mut flows_user = Vec::<u8>::with_capacity(100);
        let c = get_flows_user(flows_user.as_mut_ptr());
        flows_user.set_len(c as usize);
        let flows_user = String::from_utf8(flows_user).unwrap();

        let mut writer = Vec::new();
        let uri = format!(
            "{}/{}/send_email?sender={}",
            SENDGRID_API_PREFIX.as_str(),
            flows_user,
            encode(sender),
        );
        let uri = Uri::try_from(uri.as_str()).unwrap();
        let body = serde_json::to_vec(email).unwrap_or_default();
        match Request::new(&uri)
            .method(Method::POST)
            .header("Content-Type", "application/json")
            .header("Content-Length", &body.len())
            .body(&body)
            .send(&mut writer)
        {
            Ok(res) => {
                if !res.status_code().is_success() {
                    set_error_log(writer.as_ptr(), writer.len() as i32);
                    return Err(String::from_utf8_lossy(&writer).into_owned());
                }
            }
            Err(e) => {
                let e = e.to_string();
                set_error_log(e.as_ptr(), e.len() as i32);
                return Err(e);
            }
        }
    }
    Ok(())
}
