use crate::cmd::config::{resolve_config, ConfigArgsRef};
use crate::cmd::CliContext;
use clap::Parser;
use eternaltwin_core::types::WeakError;
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
use sqlx::PgPool;

#[derive(Debug, Parser)]
pub struct Args {
  #[clap(flatten)]
  config: crate::cmd::config::Args,
}

impl ConfigArgsRef for Args {
  fn config_args(&self) -> &crate::cmd::config::Args {
    &self.config
  }
}

pub async fn run(cx: CliContext<'_, Args>) -> Result<(), WeakError> {
  let config = resolve_config(&cx, false).await?;
  let admin_database: PgPool = PgPoolOptions::new()
    .max_connections(5)
    .connect_with(
      PgConnectOptions::new()
        .host(&config.postgres.host.value)
        .port(config.postgres.port.value)
        .database(&config.postgres.name.value)
        .username(&config.postgres.admin_user.value)
        .password(&config.postgres.admin_password.value),
    )
    .await
    .unwrap();
  eprintln!("Starting sync");
  eternaltwin_db_schema::sync(&admin_database).await.unwrap();
  eprintln!("Sync complete");
  admin_database.close().await;
  Ok(())
}
