// Copyright (C) 2026 Ordinary Labs, LLC.
//
// SPDX-License-Identifier: AGPL-3.0-only

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

#[derive(Subcommand, Debug)]
pub enum Actions {
    /// add a new action to your Ordinary project
    Add {
        /// action name
        name: String,
        /// language the action runs
        lang: String,
        /// whether the action is transactional
        transactional: Option<bool>,
    },
    /// install actions to application running on `ordinaryd` instance
    Install {
        /// name of a specific action to install (optional).
        /// will install all when the `--name` flag is not passed.
        #[arg(short, long)]
        name: Option<String>,
    },
}

impl Actions {
    pub async fn handle(
        &self,
        api_domain: Option<&str>,
        accept_invalid_certs: bool,
        project: &str,
        insecure: bool,
    ) -> anyhow::Result<()> {
        match self {
            Self::Add {
                name,
                lang,
                transactional,
            } => {
                ordinary_modify::add_action(project, name, lang, (), (), (), transactional, ())?;
            }
            Self::Install { name } => {
                let account = get_current_account(insecure)?;
                let client = OrdinaryApiClient::new(
                    &account.host,
                    &account.name,
                    api_domain,
                    accept_invalid_certs,
                    crate::USER_AGENT,
                    false,
                )?;

                if let Some(name) = name {
                    client.install(project, name).await?;
                } else {
                    client.install_all(project).await?;
                }
            }
        }

        Ok(())
    }
}
