// Define the keys used in the object storage system.

use crate::keyspace::NULLSPACEID;

pub fn index_key(keyspace_id: u32, table_id: i64, index_id: i64) -> String {
    if keyspace_id == NULLSPACEID {
        format!("t_{table_id}/i_{index_id}")
    } else {
        format!("ks_{keyspace_id}/t_{table_id}/i_{index_id}")
    }
}

pub fn shard_key(keyspace_id: u32, table_id: i64, index_id: i64, shard_id: u64) -> String {
    if keyspace_id == NULLSPACEID {
        format!("t_{table_id}/i_{index_id}/s_{shard_id}")
    } else {
        format!("ks_{keyspace_id}/t_{table_id}/i_{index_id}/s_{shard_id}")
    }
}

pub fn table_prefix(keyspace_id: u32, table_id: i64) -> String {
    if keyspace_id == NULLSPACEID {
        format!("t_{table_id}")
    } else {
        format!("ks_{keyspace_id}/t_{table_id}")
    }
}

// The S3 key for storing import input files.
pub fn import_input_prefix(
    keyspace_id: u32,
    table_id: i64,
    index_id: &[i64],
    import_job_id: u64,
) -> String {
    let index_prefix = if index_id.len() == 1 {
        format!("i_{}", index_id[0])
    } else {
        // Use "i_all" to represent multiple indexes.
        "i_all".to_string()
    };
    format!(
        "{}/{index_prefix}/import/{import_job_id}",
        table_prefix(keyspace_id, table_id)
    )
}

// The S3 key for storing fragments generated by import.
pub fn import_frags_prefix(
    keyspace_id: u32,
    table_id: i64,
    index_id: i64,
    import_job_id: u64,
) -> String {
    format!(
        "{}/i_{index_id}/import/{import_job_id}/frags",
        table_prefix(keyspace_id, table_id)
    )
}

pub fn cdc_path_prefix(prefix: &str, table_id: i64) -> String {
    format!("{prefix}/cdc/{table_id}")
}

// Converts a bucket, prefix, and key into a full S3 path, outputting it in the
// format `scheme://bucket/prefix/key`.
pub fn to_full_path(scheme: &str, bucket: &str, prefix: &str, key: &str) -> String {
    if prefix.is_empty() {
        format!("{scheme}://{bucket}/{key}")
    } else {
        format!("{scheme}://{bucket}/{prefix}/{key}")
    }
}
