#![allow(non_upper_case_globals)]

use loco_rs::prelude::*;
use serde_json::json;

static confirm: Dir<'_> = include_dir!("src/mailers/subscription/confirm");
static notification: Dir<'_> = include_dir!("src/mailers/subscription/notification");

pub struct SubscriptionMailer {}
impl Mailer for SubscriptionMailer {}

impl SubscriptionMailer {
    pub async fn send_confirmation(
        ctx: &AppContext,
        to: &str,
        site_name: Option<&str>,
        site_url: Option<&str>,
        confirm_url: &str,
        manage_url: Option<&str>,
    ) -> Result<()> {
        Self::mail_template(
            ctx,
            &confirm,
            mailer::Args {
                to: to.to_string(),
                locals: json!({
                    "subject": "请确认你的订阅",
                    "siteName": site_name.unwrap_or("Termi"),
                    "siteUrl": site_url
                        .map(ToString::to_string)
                        .unwrap_or_else(|| ctx.config.server.full_url()),
                    "confirmUrl": confirm_url,
                    "manageUrl": manage_url,
                }),
                ..Default::default()
            },
        )
        .await?;

        Ok(())
    }

    pub async fn send_notification(
        ctx: &AppContext,
        to: &str,
        subject: &str,
        headline: &str,
        body: &str,
        site_name: Option<&str>,
        site_url: Option<&str>,
        manage_url: Option<&str>,
        unsubscribe_url: Option<&str>,
    ) -> Result<()> {
        Self::mail_template(
            ctx,
            &notification,
            mailer::Args {
                to: to.to_string(),
                locals: json!({
                    "subject": subject,
                    "headline": headline,
                    "body": body,
                    "siteName": site_name.unwrap_or("Termi"),
                    "siteUrl": site_url
                        .map(ToString::to_string)
                        .unwrap_or_else(|| ctx.config.server.full_url()),
                    "manageUrl": manage_url,
                    "unsubscribeUrl": unsubscribe_url,
                }),
                ..Default::default()
            },
        )
        .await?;

        Ok(())
    }
}
