use crate::cmds::accounts::get_current_account;
use clap::Subcommand;
use ordinary_admin::client::AdminClient;
use std::error::Error;

#[derive(Subcommand)]
pub enum Templates {
    /// add a new template to the Ordinary project
    Add {
        /// template name
        name: String,
        /// HTTP route (must start with leading "/")
        route: String,
        /// MIME type for template output:
        /// [reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types)
        mime: String,
    },
    /// upload templates to application running on `ordinaryd` instance
    Upload {
        /// name of a specific template to upload (optional).
        /// will upload all when the `--name` flag is not passed.
        #[arg(short, long)]
        name: Option<String>,
    },
}

impl Templates {
    pub async fn handle(
        &self,
        host_domain: Option<&str>,
        accept_invalid_certs: bool,
        project: &str,
        insecure: bool,
    ) -> Result<(), Box<dyn Error>> {
        let account = get_current_account(insecure)?;
        let client = AdminClient::new(
            &account.host,
            &account.name,
            host_domain,
            accept_invalid_certs,
        );

        match self {
            Self::Add { name, route, mime } => {
                ordinary_modify::add_template(project, name, route, mime)?;
            }
            Self::Upload { name } => {
                if let Some(name) = name {
                    client.upload(project, name).await?;
                } else {
                    client.upload_all(project).await?;
                }
            }
        }

        Ok(())
    }
}
