//! Implements the `manta backup vcluster` command (and the deprecated
//! `manta migrate vCluster backup` alias that forwards to it).

use anyhow::{Context, Error, bail};

use crate::cli::http_client::MantaClient;
use crate::cli::output::action_result;
use manta_shared::common::app_context::AppContext;

/// Back up cluster configuration to a local bundle.
#[allow(clippy::too_many_arguments)]
pub async fn exec(
  ctx: &AppContext<'_>,
  token: &str,
  bos: Option<&str>,
  destination: Option<&str>,
  prehook: Option<&str>,
  posthook: Option<&str>,
  output_opt: Option<&str>,
) -> Result<(), Error> {
  let bos_value = bos.context("BOS template is required")?;
  let destination_value =
    destination.context("Destination folder is required")?;

  action_result::print(
    &format!(
      "Migrate backup\n BOS Template: {}\n Destination folder: {}\n Pre-hook: {}\n Post-hook: {}",
      bos_value,
      destination_value,
      prehook.unwrap_or("none"),
      posthook.unwrap_or("none"),
    ),
    output_opt,
  )?;

  if let Some(prehook_path) = prehook {
    match crate::cli::common::hooks::check_hook_perms(Some(prehook_path)) {
      Ok(_r) => {
        tracing::debug!("Pre-hook script exists and is executable.")
      }
      Err(e) => {
        bail!("{e}. File: {prehook_path}");
      }
    }
  }
  if let Some(posthook_path) = posthook {
    match crate::cli::common::hooks::check_hook_perms(Some(posthook_path)) {
      Ok(_) => {
        tracing::debug!("Post-hook script exists and is executable.")
      }
      Err(e) => {
        bail!("{e}. File: {posthook_path}");
      }
    }
  }

  if let Some(prehook_path) = prehook {
    println!("Running the pre-hook {prehook_path}");
    match crate::cli::common::hooks::run_hook(Some(prehook_path)) {
      Ok(_code) => {
        tracing::debug!("Pre-hook script completed ok. RT={}", _code)
      }
      Err(_error) => {
        bail!("Pre-hook script failed. Error: {_error}");
      }
    }
  }

  let server_url = ctx.manta_server_url;
  MantaClient::new(server_url, ctx.site_name)?
    .migrate_backup(token, bos, destination)
    .await?;
  tracing::debug!("Migrate backup completed successfully.");

  if let Some(posthook_path) = posthook {
    println!("Running the post-hook {posthook_path}");
    match crate::cli::common::hooks::run_hook(posthook) {
      Ok(_code) => {
        tracing::debug!("Post-hook script completed ok. RT={}", _code);
      }
      Err(_error) => {
        bail!("Post-hook script failed. Error: {_error}");
      }
    }
  }

  action_result::print("Backup completed", output_opt)?;

  Ok(())
}
