// Copyright (c) 2026, Salesforce, Inc.,
// All rights reserved.
// For full license text, see the LICENSE.txt file

type Buffer = u32;
const BUFFER_SIZE: usize = std::mem::size_of::<Buffer>();
const SUFFIX_LEN: usize = BUFFER_SIZE * 2;
const PREFIX: &str = "pdk-test";
const ADDED_LEN: usize = PREFIX.len() + SUFFIX_LEN + 2;

/// Generate a handle for a container.
pub fn for_container(name: &str) -> String {
    limited_handle(name, 128)
}

fn limited_handle(name: &str, max_len: usize) -> String {
    assert!(
        max_len > ADDED_LEN,
        "max_len = {max_len}, must be greater than {ADDED_LEN}"
    );

    let name_max_len = max_len - ADDED_LEN;

    // strip name if needed
    let name = if name.len() > name_max_len {
        name.split_at(name_max_len).0
    } else {
        name
    };

    handle(name)
}

/// Generate a handle for a container.
pub(crate) fn handle(name: &str) -> String {
    let mut buffer = [0u8; BUFFER_SIZE];
    getrandom::getrandom(&mut buffer).expect("should generate random");

    let suffix = Buffer::from_le_bytes(buffer);

    format!("{PREFIX}-{name}-{suffix:08x}")
}

#[cfg(test)]
mod tests {
    use crate::handle::SUFFIX_LEN;

    use super::{Buffer, PREFIX};

    fn assert_preffix(handle: &str, name: &str) {
        assert!(handle.starts_with(&format!("{PREFIX}-{name}-")));
    }

    fn assert_suffix(handle: &str) {
        let suffix = handle.split('-').next_back().unwrap();
        assert_eq!(suffix.len(), SUFFIX_LEN);

        let suffix = Buffer::from_str_radix(suffix, 16);
        assert!(suffix.is_ok());
    }

    #[test]
    fn limited_handle() {
        let handle = super::limited_handle("flex", 30);

        assert_preffix(&handle, "flex");
        assert_suffix(&handle);
    }

    #[test]
    fn limited_handle_with_strip() {
        let handle = super::limited_handle("flex", 20);

        assert_preffix(&handle, "fl");
        assert_suffix(&handle);
    }
}
