#![allow(
    clippy::unwrap_in_result,
    reason = "unwraps are allowed anywhere in tests"
)]
#![allow(
    clippy::indexing_slicing,
    reason = "unwraps are allowed anywhere in tests"
)]

use std::assert_matches;

use super::{Code, CodeSet, Warning};
use crate::{
    json::{self, FromJson as _},
    warning::test::VerdictTestExt as _,
    Verdict,
};

impl Code {
    /// Return a `country::Code` for the given `str`.
    ///
    /// # Panics
    ///
    /// Will panic when the given `str` is not two bytes long or an unknown country code.
    pub fn from_alpha_2_str(code: &str) -> Self {
        let bytes = code.as_bytes();

        // ISO 3166-1 is expected to be 2 chars.
        let [a, b] = bytes else {
            panic!(
                "Unable to parse country code. Expected length of 2 chars. It has length: `{}`",
                code.len()
            );
        };

        let couplet: [u8; 2] = [a.to_ascii_uppercase(), b.to_ascii_uppercase()];

        let Some(code) = Code::from_alpha_2(couplet) else {
            panic!("Unknown country code `{code}`");
        };

        code
    }
}

#[test]
fn alpha2_country_code_matches() {
    let code = Code::from_alpha_2(*b"NL").unwrap();

    assert_eq!(Code::Nl, code);
    assert_eq!("NL", code.into_alpha_2_str());
}

#[test]
fn alpha3_country_code_matches() {
    let code = Code::from_alpha_3(*b"NLD").unwrap();

    assert_eq!(Code::Nl, code);
}

#[test]
fn should_create_country3_without_issue() {
    const JSON: &str = r#"{ "country": "NLD" }"#;

    let (code_set, warnings) = code_set_from_json(JSON).unwrap().into_parts();

    let CodeSet::Alpha3(code) = code_set else {
        panic!("expected Alpha3, got {code_set:?}");
    };
    assert_eq!(code, Code::Nl);
    assert!(warnings.is_empty(), "{:#?}", warnings.path_id_map());
}

#[test]
fn should_create_country2_without_issue() {
    const JSON: &str = r#"{ "country": "NL" }"#;

    let (code_set, warnings) = code_set_from_json(JSON).unwrap().into_parts();

    let CodeSet::Alpha2(code) = code_set else {
        panic!("expected Alpha2, got {code_set:?}");
    };
    assert_eq!(code, Code::Nl);
    assert!(warnings.is_empty(), "{:#?}", warnings.path_id_map());
}

#[test]
fn should_raise_country_content_issue() {
    {
        const JSON: &str = r#"{ "country": "VV" }"#;

        let error = code_set_from_json(JSON).unwrap_only_error();

        assert_matches!(error.into_warning(), Warning::InvalidCode);
    }

    {
        const JSON: &str = r#"{ "country": "VVV" }"#;

        let error = code_set_from_json(JSON).unwrap_only_error();

        assert_matches!(error.into_warning(), Warning::InvalidCode);
    }
}

#[test]
fn should_parse_invalid_case() {
    {
        const JSON: &str = r#"{ "country": "nl" }"#;

        let (code_set, warnings) = code_set_from_json(JSON).unwrap().into_parts();
        let warnings = warnings.path_map();
        let warnings = &*warnings["$.country"];

        let CodeSet::Alpha2(code) = code_set else {
            panic!("expected Alpha2, got {code_set:?}");
        };
        assert_eq!(code, Code::Nl);
        assert_matches!(*warnings, [Warning::PreferUpperCase]);
    }

    {
        const JSON: &str = r#"{ "country": "nld" }"#;

        let (code_set, warnings) = code_set_from_json(JSON).unwrap().into_parts();
        let warnings = warnings.path_map();
        let warnings = &*warnings["$.country"];

        let CodeSet::Alpha3(code) = code_set else {
            panic!("expected Alpha3, got {code_set:?}");
        };
        assert_eq!(code, Code::Nl);
        assert_matches!(warnings, [Warning::PreferUpperCase]);
    }
}

#[test]
fn should_raise_country_length_issue() {
    const JSON: &str = r#"{ "country": "IRELAND" }"#;

    let error = code_set_from_json(JSON).unwrap_only_error();

    assert_matches!(error.into_warning(), Warning::InvalidLength);
}

#[track_caller]
fn code_set_from_json(json: &str) -> Verdict<CodeSet, Warning> {
    let doc = json::parse(json.into()).unwrap();
    let country_elem = doc.root().find_field("country").unwrap();
    CodeSet::from_json(country_elem.element())
}
