//! S3 client construction with credential and region configuration.

use aws_config::BehaviorVersion;
use aws_sdk_s3::Client;

use crate::error::Result;

/// Build an S3 client using the default credential chain.
///
/// Optionally override the AWS profile and region.
pub async fn build_client(profile: Option<&str>, region: Option<&str>) -> Result<Client> {
    let mut loader = aws_config::defaults(BehaviorVersion::latest());

    if let Some(profile) = profile {
        loader = loader.profile_name(profile);
    }

    if let Some(region) = region {
        loader = loader.region(aws_config::Region::new(region.to_owned()));
    }

    let config = loader.load().await;
    Ok(Client::new(&config))
}

/// Holds separate clients for source and destination,
/// supporting cross-account copies with different profiles.
#[derive(Debug, Clone)]
pub struct DualClient {
    pub source: Client,
    pub destination: Client,
}

impl DualClient {
    /// Build a `DualClient` from optional profile/region overrides.
    ///
    /// If source and destination profiles are both `None`, a single
    /// client is shared for both.
    pub async fn new(
        source_profile: Option<&str>,
        dest_profile: Option<&str>,
        source_region: Option<&str>,
        dest_region: Option<&str>,
    ) -> Result<Self> {
        let source = build_client(source_profile, source_region).await?;

        // Reuse the same client if profiles and regions match.
        let destination = if source_profile == dest_profile && source_region == dest_region {
            source.clone()
        } else {
            build_client(dest_profile, dest_region).await?
        };

        Ok(Self {
            source,
            destination,
        })
    }
}
