#![cfg(feature = "env-utf8")]
// SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
// SPDX-License-Identifier: BSD-2-Clause
//! Test the helper functions for preparing a UTF-8-capable environment.

#![expect(clippy::tests_outside_test_module, reason = "integration test")]

use std::collections::HashMap;
use std::env as std_env;

use itertools::Itertools as _;

use roundlet::env;

#[test]
/// Make sure [`c_utf8_vars()`] returns a sensible result.
#[expect(clippy::indexing_slicing, reason = "we hope these are the variables")]
#[expect(
    clippy::case_sensitive_file_extension_comparisons,
    reason = "not a file extension at all; also, case-insensitive"
)]
fn check_c_utf8_vars() {
    let vars_vec: Vec<_> = env::c_utf8_vars().collect();
    assert_eq!(vars_vec.len(), 2_usize, "{vars_vec:?}");
    let vars_map: HashMap<_, _> = vars_vec.into_iter().collect();
    assert_eq!(
        vars_map.keys().copied().sorted().collect::<Vec<_>>(),
        ["LANGUAGE", "LC_ALL"],
        "{vars_map:?}"
    );
    assert_eq!(vars_map["LANGUAGE"], "", "{vars_map:?}");
    let locale = vars_map["LC_ALL"].to_ascii_lowercase();
    assert!(
        locale.ends_with(".utf8") || locale.ends_with(".utf-8"),
        "{vars_map:?} {locale:?}"
    );
}

#[test]
/// Make sure [`c_utf8_add_vars()`] returns a sensible result.
#[expect(
    clippy::indexing_slicing,
    reason = "we really hope there are two variables"
)]
fn check_c_utf8_add_vars() {
    let env_map: HashMap<String, String> = std_env::vars().collect();
    let expected = {
        let mut expected: HashMap<String, String> = env_map.clone();
        let vars: Vec<_> = env::c_utf8_vars().collect();
        // So this is so hardcoded, but it will work...
        expected.insert(vars[0_usize].0.to_owned(), vars[0_usize].1.to_owned());
        expected.insert(vars[1_usize].0.to_owned(), vars[1_usize].1.to_owned());
        expected
    };

    let env_u8_map: HashMap<String, String> = env::c_utf8_add_vars(env_map).collect();
    assert_eq!(
        env_u8_map, expected,
        "expected: {expected:?}  got: {env_u8_map:?}"
    );
}
