use crate::cmds::accounts::get_current_account;
use clap::Subcommand;
use ordinary_api::client::OrdinaryApiClient;
use std::error::Error;

#[derive(Subcommand)]
pub enum Content {
    /// manage content definitions for Ordinary project
    Definition {
        #[command(subcommand)]
        definition: Definition,
    },
    /// manage content objects for Ordinary project
    Object {
        #[command(subcommand)]
        object: Object,
    },
    /// update content for application running on `ordinaryd` instance
    Put,
}

#[derive(Subcommand)]
pub enum Definition {
    /// add a content definition to your Ordinary project
    Add {
        /// content definition / instance name
        name: String,
    },
}

#[derive(Subcommand)]
pub enum Object {
    /// add a content object to your Ordinary project
    Add {
        /// json value of content object
        json: String,
    },
}

impl Content {
    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 = OrdinaryApiClient::new(
            &account.host,
            &account.name,
            host_domain,
            accept_invalid_certs,
        );

        match self {
            Self::Definition { definition } => match definition {
                Definition::Add { name } => {
                    ordinary_modify::add_content_def(project, name)?;
                }
            },
            Self::Object { object } => match object {
                Object::Add { json } => {
                    ordinary_modify::add_content_def(project, json)?;
                }
            },
            Self::Put => {
                client.update(project).await?;
            }
        }

        Ok(())
    }
}
