use anyhow::*;
use clap::{Parser, ValueEnum};

#[derive(Parser)]
pub enum SubCommand {
	#[clap(alias = "sh")]
	Shell {
		#[clap(index = 1)]
		database_type: DatabaseType,
		#[clap(index = 2)]
		service: String,
		#[clap(short = 'q', long)]
		query: Option<String>,
	},
	Nuke {
		#[clap(long)]
		yes: bool,
	},
}

#[derive(ValueEnum, Clone, PartialEq)]
pub enum DatabaseType {
	#[clap(alias = "ch")]
	Clickhouse,
}

impl SubCommand {
	pub async fn execute(self, config: rivet_config::Config) -> Result<()> {
		match self {
			Self::Shell {
				database_type: db_type,
				service,
				query,
			} => {
				let shell_query = crate::util::db::ShellQuery {
					svc: service,
					query,
				};
				let shell_ctx = crate::util::db::ShellContext {
					queries: &[shell_query],
				};

				match db_type {
					DatabaseType::Clickhouse => {
						crate::util::db::clickhouse_shell(config, shell_ctx).await?
					}
				}

				Ok(())
			}
			Self::Nuke { yes } => {
				if !yes {
					bail!("Please pass '--yes' flag to confirm you want to nuke the database");
				}

				match config.database() {
					rivet_config::config::Database::Postgres(_) => {
						bail!("nuke postgres not implemented");
					}
					rivet_config::config::Database::FileSystem(file_system) => {
						println!("Removing {}", file_system.path.display());
						tokio::fs::remove_dir_all(&file_system.path).await?;
						println!("Complete");
						Ok(())
					}
				}
			}
		}
	}
}
