use chrono::{DateTime, Utc};
use serde::Serialize;
use serde_json::Value;
use sqlx::{FromRow, PgPool};
use std::env;
use thiserror::Error;
use uuid::Uuid;

use crate::schema::ensure_storage_runtime_schema;

const STORAGE_SECRET_KEY_ENV: &str = "ATHENA_STORAGE_SECRET_ENCRYPTION_KEY";

#[derive(FromRow)]
struct S3CredentialSecretRecord {
    access_key_id: String,
    secret_key: String,
    session_token: Option<String>,
}

#[derive(Debug, Error)]
pub enum S3CredentialStoreError {
    #[error("database error: {0}")]
    Database(#[from] sqlx::Error),
    #[error("schema self-heal error: {0}")]
    SchemaHeal(#[from] athena_schema_heal::SchemaHealError),
    #[error("s3 catalog entry not found")]
    NotFound,
    #[error("access denied")]
    AccessDenied,
    #[error("active s3 credential not found")]
    MissingActiveCredential,
    #[error("{0}")]
    InvalidInput(String),
}

#[derive(Debug, Clone)]
pub struct CreateS3CatalogInput {
    pub name: String,
    pub description: String,
    pub endpoint: String,
    pub region: String,
    pub bucket: Option<String>,
    pub provider: String,
    pub force_path_style: bool,
    pub default_prefix: Option<String>,
    pub public_base_url: Option<String>,
    pub access_key_id: String,
    pub secret_key: String,
    pub session_token: Option<String>,
    pub metadata: Value,
}

#[derive(Debug, Clone, Default)]
pub struct UpdateS3CatalogInput {
    pub name: Option<String>,
    pub description: Option<String>,
    pub endpoint: Option<String>,
    pub region: Option<String>,
    pub bucket: Option<String>,
    pub provider: Option<String>,
    pub force_path_style: Option<bool>,
    pub default_prefix: Option<String>,
    pub public_base_url: Option<String>,
    pub access_key_id: Option<String>,
    pub secret_key: Option<String>,
    pub session_token: Option<String>,
    pub is_active: Option<bool>,
    pub metadata: Option<Value>,
}

#[derive(FromRow)]
struct S3CatalogRecord {
    id: Uuid,
    name: String,
    description: String,
    endpoint: Option<String>,
    region: Option<String>,
    bucket: String,
    provider: String,
    force_path_style: bool,
    default_prefix: Option<String>,
    public_base_url: Option<String>,
    is_active: bool,
    metadata: Value,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
    active_credential_id: Option<Uuid>,
    active_access_key_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct S3CatalogItem {
    pub id: String,
    pub name: String,
    pub description: String,
    pub endpoint: Option<String>,
    pub region: Option<String>,
    pub bucket: String,
    pub provider: String,
    pub force_path_style: bool,
    pub default_prefix: Option<String>,
    pub public_base_url: Option<String>,
    pub is_active: bool,
    pub metadata: Value,
    pub active_credential_id: Option<String>,
    pub active_access_key: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Clone)]
pub struct S3CatalogRuntimeBinding {
    pub catalog: S3CatalogItem,
    pub access_key_id: String,
    pub secret_key: String,
    pub session_token: Option<String>,
}

impl std::fmt::Debug for S3CatalogRuntimeBinding {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("S3CatalogRuntimeBinding")
            .field("catalog", &self.catalog)
            .field("access_key_id", &self.access_key_id)
            .field("secret_key", &"<redacted>")
            .field(
                "session_token",
                &self.session_token.as_ref().map(|_| "<redacted>"),
            )
            .finish()
    }
}

impl From<S3CatalogRecord> for S3CatalogItem {
    fn from(value: S3CatalogRecord) -> Self {
        Self {
            id: value.id.to_string(),
            name: value.name,
            description: value.description,
            endpoint: value.endpoint,
            region: value.region,
            bucket: value.bucket,
            provider: value.provider,
            force_path_style: value.force_path_style,
            default_prefix: value.default_prefix,
            public_base_url: value.public_base_url,
            is_active: value.is_active,
            metadata: value.metadata,
            active_credential_id: value.active_credential_id.map(|id| id.to_string()),
            active_access_key: value.active_access_key_id,
            created_at: value.created_at,
            updated_at: value.updated_at,
        }
    }
}

#[derive(FromRow)]
struct S3CatalogRuntimeRecord {
    id: Uuid,
    name: String,
    description: String,
    endpoint: Option<String>,
    region: Option<String>,
    bucket: String,
    provider: String,
    force_path_style: bool,
    default_prefix: Option<String>,
    public_base_url: Option<String>,
    is_active: bool,
    metadata: Value,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
    active_credential_id: Uuid,
    active_access_key_id: String,
    secret_key: String,
    session_token: Option<String>,
}

impl From<S3CatalogRuntimeRecord> for S3CatalogRuntimeBinding {
    fn from(value: S3CatalogRuntimeRecord) -> Self {
        let catalog = S3CatalogItem {
            id: value.id.to_string(),
            name: value.name,
            description: value.description,
            endpoint: value.endpoint,
            region: value.region,
            bucket: value.bucket,
            provider: value.provider,
            force_path_style: value.force_path_style,
            default_prefix: value.default_prefix,
            public_base_url: value.public_base_url,
            is_active: value.is_active,
            metadata: value.metadata,
            active_credential_id: Some(value.active_credential_id.to_string()),
            active_access_key: Some(value.active_access_key_id.clone()),
            created_at: value.created_at,
            updated_at: value.updated_at,
        };

        Self {
            catalog,
            access_key_id: value.active_access_key_id,
            secret_key: value.secret_key,
            session_token: value.session_token,
        }
    }
}

#[derive(FromRow)]
struct S3CredentialRecord {
    id: Uuid,
    catalog_id: Uuid,
    name: String,
    description: String,
    endpoint: Option<String>,
    region: Option<String>,
    bucket: String,
    provider: String,
    access_key_id: String,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct S3CredentialListItem {
    pub id: String,
    pub s3_id: String,
    pub name: String,
    pub description: String,
    pub endpoint: Option<String>,
    pub region: Option<String>,
    pub bucket: String,
    pub provider: String,
    pub access_key: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

impl From<S3CredentialRecord> for S3CredentialListItem {
    fn from(value: S3CredentialRecord) -> Self {
        Self {
            id: value.id.to_string(),
            s3_id: value.catalog_id.to_string(),
            name: value.name,
            description: value.description,
            endpoint: value.endpoint,
            region: value.region,
            bucket: value.bucket,
            provider: value.provider,
            access_key: value.access_key_id,
            created_at: value.created_at,
            updated_at: value.updated_at,
        }
    }
}

pub async fn ensure_s3_credentials_table(pool: &PgPool) -> Result<(), S3CredentialStoreError> {
    ensure_storage_runtime_schema(pool).await?;
    Ok(())
}

pub async fn list_s3_catalogs(pool: &PgPool) -> Result<Vec<S3CatalogItem>, S3CredentialStoreError> {
    ensure_s3_credentials_table(pool).await?;

    let rows = sqlx::query_as::<_, S3CatalogRecord>(
        r#"
        SELECT
            s.id,
            s.name,
            s.description,
            s.endpoint,
            s.region,
            s.bucket,
            s.provider,
            s.force_path_style,
            s.default_prefix,
            s.public_base_url,
            s.is_active,
            s.metadata,
            s.created_at,
            s.updated_at,
            c.active_credential_id,
            c.active_access_key_id
        FROM athena.s3_catalogs AS s
        LEFT JOIN LATERAL (
            SELECT
                id AS active_credential_id,
                access_key_id AS active_access_key_id
            FROM athena.s3_credentials
            WHERE catalog_id = s.id
              AND is_active = true
            ORDER BY created_at DESC, id DESC
            LIMIT 1
        ) AS c ON true
        WHERE s.deleted_at IS NULL
        ORDER BY s.created_at DESC, s.id DESC
        "#,
    )
    .fetch_all(pool)
    .await?;

    Ok(rows.into_iter().map(Into::into).collect())
}

pub async fn create_s3_catalog(
    pool: &PgPool,
    input: &CreateS3CatalogInput,
) -> Result<S3CatalogItem, S3CredentialStoreError> {
    ensure_s3_credentials_table(pool).await?;

    let bucket = normalize_required(input.bucket.as_deref(), "bucket")?;
    let encryption_key = storage_secret_encryption_key()?;

    let mut tx = pool.begin().await?;
    let catalog_id = Uuid::new_v4();
    let credential_id = Uuid::new_v4();

    sqlx::query(
        r#"
        INSERT INTO athena.s3_catalogs (
            id,
            name,
            provider,
            bucket,
            region,
            endpoint,
            force_path_style,
            default_prefix,
            public_base_url,
            description,
            is_active,
            metadata
        )
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, true, $11)
        "#,
    )
    .bind(catalog_id)
    .bind(normalize_required(Some(&input.name), "name")?)
    .bind(normalize_required(Some(&input.provider), "provider")?)
    .bind(bucket)
    .bind(normalize_optional(Some(input.region.as_str())))
    .bind(normalize_optional(Some(input.endpoint.as_str())))
    .bind(input.force_path_style)
    .bind(normalize_optional(input.default_prefix.as_deref()))
    .bind(normalize_optional(input.public_base_url.as_deref()))
    .bind(input.description.trim())
    .bind(normalize_metadata_object(input.metadata.clone()))
    .execute(&mut *tx)
    .await?;

    sqlx::query(
        r#"
        INSERT INTO athena.s3_credentials (
            id,
            catalog_id,
            access_key_id,
            secret_key_encrypted,
            session_token_encrypted,
            is_active,
            metadata
        )
        VALUES (
            $1,
            $2,
            $3,
            armor(pgp_sym_encrypt($4, $5)),
            CASE
                WHEN $6::text IS NULL THEN NULL
                ELSE armor(pgp_sym_encrypt($6, $5))
            END,
            true,
            $7
        )
        "#,
    )
    .bind(credential_id)
    .bind(catalog_id)
    .bind(normalize_required(
        Some(&input.access_key_id),
        "access_key_id",
    )?)
    .bind(normalize_required(Some(&input.secret_key), "secret_key")?)
    .bind(&encryption_key)
    .bind(normalize_optional(input.session_token.as_deref()))
    .bind(normalize_metadata_object(input.metadata.clone()))
    .execute(&mut *tx)
    .await?;

    tx.commit().await?;
    load_s3_catalog(pool, catalog_id).await
}

pub async fn update_s3_catalog(
    pool: &PgPool,
    s3_id: Uuid,
    input: &UpdateS3CatalogInput,
) -> Result<S3CatalogItem, S3CredentialStoreError> {
    ensure_s3_credentials_table(pool).await?;

    let mut tx = pool.begin().await?;
    let metadata = input.metadata.clone();

    let updated = sqlx::query(
        r#"
        UPDATE athena.s3_catalogs
        SET
            name = COALESCE($2, name),
            provider = COALESCE($3, provider),
            bucket = COALESCE($4, bucket),
            region = COALESCE($5, region),
            endpoint = COALESCE($6, endpoint),
            force_path_style = COALESCE($7, force_path_style),
            default_prefix = COALESCE($8, default_prefix),
            public_base_url = COALESCE($9, public_base_url),
            description = COALESCE($10, description),
            is_active = COALESCE($11, is_active),
            metadata = CASE
                WHEN $12::jsonb IS NULL THEN metadata
                ELSE COALESCE(metadata, '{}'::jsonb) || $12::jsonb
            END,
            updated_at = now()
        WHERE id = $1
          AND deleted_at IS NULL
        "#,
    )
    .bind(s3_id)
    .bind(normalize_optional(input.name.as_deref()))
    .bind(normalize_optional(input.provider.as_deref()))
    .bind(normalize_optional(input.bucket.as_deref()))
    .bind(normalize_optional(input.region.as_deref()))
    .bind(normalize_optional(input.endpoint.as_deref()))
    .bind(input.force_path_style)
    .bind(normalize_optional(input.default_prefix.as_deref()))
    .bind(normalize_optional(input.public_base_url.as_deref()))
    .bind(normalize_optional(input.description.as_deref()))
    .bind(input.is_active)
    .bind(metadata.map(normalize_metadata_object))
    .execute(&mut *tx)
    .await?;

    if updated.rows_affected() == 0 {
        return Err(S3CredentialStoreError::NotFound);
    }

    if input.is_active == Some(false) {
        sqlx::query(
            r#"
            UPDATE athena.s3_credentials
            SET is_active = false, updated_at = now(), rotated_at = COALESCE(rotated_at, now())
            WHERE catalog_id = $1
              AND is_active = true
            "#,
        )
        .bind(s3_id)
        .execute(&mut *tx)
        .await?;
    }

    if input.access_key_id.is_some() || input.secret_key.is_some() || input.session_token.is_some()
    {
        let encryption_key = storage_secret_encryption_key()?;

        let existing = sqlx::query_as::<_, S3CredentialSecretRecord>(
            r#"
            SELECT
                access_key_id,
                pgp_sym_decrypt(dearmor(secret_key_encrypted), $2)::text AS secret_key,
                CASE
                    WHEN session_token_encrypted IS NULL THEN NULL
                    ELSE pgp_sym_decrypt(dearmor(session_token_encrypted), $2)::text
                END AS session_token
            FROM athena.s3_credentials
            WHERE catalog_id = $1
            ORDER BY created_at DESC, id DESC
            LIMIT 1
            "#,
        )
        .bind(s3_id)
        .bind(&encryption_key)
        .fetch_optional(&mut *tx)
        .await?;

        let Some(existing) = existing else {
            return Err(S3CredentialStoreError::MissingActiveCredential);
        };

        sqlx::query(
            r#"
            UPDATE athena.s3_credentials
            SET
                is_active = false,
                updated_at = now(),
                rotated_at = COALESCE(rotated_at, now())
            WHERE catalog_id = $1
              AND is_active = true
            "#,
        )
        .bind(s3_id)
        .execute(&mut *tx)
        .await?;

        sqlx::query(
            r#"
            INSERT INTO athena.s3_credentials (
                id,
                catalog_id,
                access_key_id,
                secret_key_encrypted,
                session_token_encrypted,
                is_active,
                metadata
            )
            VALUES (
                $1,
                $2,
                $3,
                armor(pgp_sym_encrypt($4, $5)),
                CASE
                    WHEN $6::text IS NULL THEN NULL
                    ELSE armor(pgp_sym_encrypt($6, $5))
                END,
                COALESCE($7, true),
                COALESCE($8, '{}'::jsonb)
            )
            "#,
        )
        .bind(Uuid::new_v4())
        .bind(s3_id)
        .bind(
            input
                .access_key_id
                .clone()
                .or_else(|| Some(existing.access_key_id.clone()))
                .ok_or_else(|| {
                    S3CredentialStoreError::InvalidInput(
                        "access_key_id is required for credential rotation".to_string(),
                    )
                })?,
        )
        .bind(
            input
                .secret_key
                .clone()
                .or_else(|| Some(existing.secret_key.clone()))
                .ok_or_else(|| {
                    S3CredentialStoreError::InvalidInput(
                        "secret_key is required for credential rotation".to_string(),
                    )
                })?,
        )
        .bind(&encryption_key)
        .bind(input.session_token.clone().or(existing.session_token))
        .bind(input.is_active)
        .bind(
            input
                .metadata
                .clone()
                .map(normalize_metadata_object)
                .unwrap_or_else(|| Value::Object(Default::default())),
        )
        .execute(&mut *tx)
        .await?;
    }

    tx.commit().await?;
    load_s3_catalog(pool, s3_id).await
}

pub async fn delete_s3_catalog(pool: &PgPool, s3_id: Uuid) -> Result<(), S3CredentialStoreError> {
    ensure_s3_credentials_table(pool).await?;

    let mut tx = pool.begin().await?;
    let updated = sqlx::query(
        r#"
        UPDATE athena.s3_catalogs
        SET
            is_active = false,
            updated_at = now(),
            deleted_at = COALESCE(deleted_at, now())
        WHERE id = $1
          AND deleted_at IS NULL
        "#,
    )
    .bind(s3_id)
    .execute(&mut *tx)
    .await?;

    if updated.rows_affected() == 0 {
        return Err(S3CredentialStoreError::NotFound);
    }

    sqlx::query(
        r#"
        UPDATE athena.s3_credentials
        SET is_active = false, updated_at = now(), rotated_at = COALESCE(rotated_at, now())
        WHERE catalog_id = $1
        "#,
    )
    .bind(s3_id)
    .execute(&mut *tx)
    .await?;

    tx.commit().await?;
    Ok(())
}

pub async fn list_s3_credentials(
    pool: &PgPool,
) -> Result<Vec<S3CredentialListItem>, S3CredentialStoreError> {
    ensure_s3_credentials_table(pool).await?;

    let rows = sqlx::query_as::<_, S3CredentialRecord>(
        r#"
        SELECT
            c.id,
            c.catalog_id,
            s.name,
            s.description,
            s.endpoint,
            s.region,
            s.bucket,
            s.provider,
            c.access_key_id,
            c.created_at,
            c.updated_at
        FROM athena.s3_credentials AS c
        INNER JOIN athena.s3_catalogs AS s
            ON s.id = c.catalog_id
        WHERE c.is_active = true
          AND s.deleted_at IS NULL
        ORDER BY c.created_at DESC, c.id DESC
        "#,
    )
    .fetch_all(pool)
    .await?;

    Ok(rows.into_iter().map(Into::into).collect())
}

pub async fn load_s3_catalog_runtime(
    pool: &PgPool,
    s3_id: Uuid,
) -> Result<S3CatalogRuntimeBinding, S3CredentialStoreError> {
    ensure_s3_credentials_table(pool).await?;
    let encryption_key = storage_secret_encryption_key()?;

    let row = sqlx::query_as::<_, S3CatalogRuntimeRecord>(
        r#"
        SELECT
            s.id,
            s.name,
            s.description,
            s.endpoint,
            s.region,
            s.bucket,
            s.provider,
            s.force_path_style,
            s.default_prefix,
            s.public_base_url,
            s.is_active,
            s.metadata,
            s.created_at,
            s.updated_at,
            c.id AS active_credential_id,
            c.access_key_id AS active_access_key_id,
            pgp_sym_decrypt(dearmor(c.secret_key_encrypted), $2)::text AS secret_key,
            CASE
                WHEN c.session_token_encrypted IS NULL THEN NULL
                ELSE pgp_sym_decrypt(dearmor(c.session_token_encrypted), $2)::text
            END AS session_token
        FROM athena.s3_catalogs AS s
        INNER JOIN athena.s3_credentials AS c
            ON c.catalog_id = s.id
           AND c.is_active = true
        WHERE s.id = $1
          AND s.deleted_at IS NULL
          AND s.is_active = true
        ORDER BY c.created_at DESC, c.id DESC
        LIMIT 1
        "#,
    )
    .bind(s3_id)
    .bind(&encryption_key)
    .fetch_optional(pool)
    .await?;

    row.map(Into::into)
        .ok_or(S3CredentialStoreError::MissingActiveCredential)
}

async fn load_s3_catalog(
    pool: &PgPool,
    s3_id: Uuid,
) -> Result<S3CatalogItem, S3CredentialStoreError> {
    let row = sqlx::query_as::<_, S3CatalogRecord>(
        r#"
        SELECT
            s.id,
            s.name,
            s.description,
            s.endpoint,
            s.region,
            s.bucket,
            s.provider,
            s.force_path_style,
            s.default_prefix,
            s.public_base_url,
            s.is_active,
            s.metadata,
            s.created_at,
            s.updated_at,
            c.active_credential_id,
            c.active_access_key_id
        FROM athena.s3_catalogs AS s
        LEFT JOIN LATERAL (
            SELECT
                id AS active_credential_id,
                access_key_id AS active_access_key_id
            FROM athena.s3_credentials
            WHERE catalog_id = s.id
              AND is_active = true
            ORDER BY created_at DESC, id DESC
            LIMIT 1
        ) AS c ON true
        WHERE s.id = $1
          AND s.deleted_at IS NULL
        "#,
    )
    .bind(s3_id)
    .fetch_optional(pool)
    .await?;

    row.map(Into::into).ok_or(S3CredentialStoreError::NotFound)
}

fn normalize_required(value: Option<&str>, field: &str) -> Result<String, S3CredentialStoreError> {
    let Some(value) = normalize_optional(value) else {
        return Err(S3CredentialStoreError::InvalidInput(format!(
            "{field} is required"
        )));
    };
    Ok(value)
}

fn normalize_optional(value: Option<&str>) -> Option<String> {
    value
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string)
}

fn normalize_metadata_object(value: Value) -> Value {
    match value {
        Value::Object(map) => Value::Object(map),
        _ => Value::Object(Default::default()),
    }
}

fn storage_secret_encryption_key() -> Result<String, S3CredentialStoreError> {
    normalize_optional(env::var(STORAGE_SECRET_KEY_ENV).ok().as_deref()).ok_or_else(|| {
        S3CredentialStoreError::InvalidInput(format!(
            "{STORAGE_SECRET_KEY_ENV} must be set to encrypt Athena storage credentials"
        ))
    })
}

#[cfg(test)]
mod tests {
    use chrono::DateTime;
    use serde_json::json;

    use super::{S3CatalogItem, S3CatalogRecord, S3CredentialListItem, S3CredentialRecord};

    #[test]
    fn list_item_maps_access_key_id_to_public_field() {
        let record = S3CredentialRecord {
            id: uuid::Uuid::parse_str("8f9d00bb-5ca8-4664-847f-1ccaa1c8239c").unwrap(),
            catalog_id: uuid::Uuid::parse_str("4338db57-cc09-48dc-9db5-41b6b8181e80").unwrap(),
            name: "primary".to_string(),
            description: "primary".to_string(),
            endpoint: Some("https://s3.example.com".to_string()),
            region: Some("eu-west-1".to_string()),
            bucket: "backups".to_string(),
            provider: "s3".to_string(),
            access_key_id: "AKIA_TEST".to_string(),
            created_at: DateTime::parse_from_rfc3339("2026-06-13T11:12:13Z")
                .unwrap()
                .with_timezone(&chrono::Utc),
            updated_at: DateTime::parse_from_rfc3339("2026-06-13T11:12:14Z")
                .unwrap()
                .with_timezone(&chrono::Utc),
        };

        let item = S3CredentialListItem::from(record);

        assert_eq!(item.description, "primary");
        assert_eq!(item.access_key, "AKIA_TEST");
        assert_eq!(item.name, "primary");
        assert_eq!(item.bucket, "backups");
        assert_eq!(item.s3_id, "4338db57-cc09-48dc-9db5-41b6b8181e80");
    }

    #[test]
    fn catalog_item_maps_active_credential_fields() {
        let record = S3CatalogRecord {
            id: uuid::Uuid::parse_str("8f9d00bb-5ca8-4664-847f-1ccaa1c8239c").unwrap(),
            name: "prod-objects".to_string(),
            description: "primary".to_string(),
            endpoint: Some("https://s3.example.com".to_string()),
            region: Some("eu-west-1".to_string()),
            bucket: "backups".to_string(),
            provider: "s3".to_string(),
            force_path_style: false,
            default_prefix: Some("reports".to_string()),
            public_base_url: Some("https://cdn.example.com".to_string()),
            is_active: true,
            metadata: json!({ "scope": "prod" }),
            created_at: DateTime::parse_from_rfc3339("2026-06-13T11:12:13Z")
                .unwrap()
                .with_timezone(&chrono::Utc),
            updated_at: DateTime::parse_from_rfc3339("2026-06-13T11:12:14Z")
                .unwrap()
                .with_timezone(&chrono::Utc),
            active_credential_id: Some(
                uuid::Uuid::parse_str("4338db57-cc09-48dc-9db5-41b6b8181e80").unwrap(),
            ),
            active_access_key_id: Some("AKIA_TEST".to_string()),
        };

        let item = S3CatalogItem::from(record);

        assert_eq!(item.bucket, "backups");
        assert_eq!(
            item.public_base_url.as_deref(),
            Some("https://cdn.example.com")
        );
        assert_eq!(item.active_access_key.as_deref(), Some("AKIA_TEST"));
        assert_eq!(
            item.active_credential_id.as_deref(),
            Some("4338db57-cc09-48dc-9db5-41b6b8181e80")
        );
    }
}
