use std::path::Path;

#[expect(
    clippy::unused_trait_names,
    reason = "This is a bug in Clippy. It is not seeing the use of Versioned in the generic bounds below"
)]
use crate::{
    guess,
    json::FromJson,
    tariff,
    test::{self, VersionedType},
    Versioned,
};

#[test_each::file(
    glob = "ocpi-tariffs/test_data/v211/real_world/*/tariff*.json",
    name(segments = 2)
)]
fn should_parse_v211_tariff(tariff_json: &str, path: &Path) {
    test::setup();

    parse_tariff::<super::v211::Tariff<'_>>(tariff_json, path);
}

#[test_each::file(
    glob = "ocpi-tariffs/test_data/v221/real_world/*/tariff*.json",
    name(segments = 2)
)]
fn should_parse_v221_tariff(tariff_json: &str, path: &Path) {
    test::setup();

    parse_tariff::<super::v221::Tariff<'_>>(tariff_json, path);
}

#[track_caller]
fn parse_tariff<'buf, T>(tariff_json: &'buf str, path: &Path)
where
    T: VersionedType + FromJson<'buf, Warning = tariff::Warning>,
{
    {
        // Assert that all the tariffs in the real_world folder are inferred/guessed correctly.
        let doc = crate::json::parse_object(tariff_json).unwrap();
        let guess = tariff::infer_version(doc);
        let guess::Version::Certain(tariff) = &guess else {
            panic!("expected a certain version, got {guess:?}");
        };
        assert_eq!(tariff.version(), T::VERSION);
    }

    let expect_json = test::read_expect_json(path, "parse");

    let doc = crate::json::parse_object(tariff_json).unwrap();
    let (tariff_elem, warnings) = tariff::build(doc, T::VERSION).into_parts();

    {
        let parse_expect = test::parse_expect_json(expect_json.as_deref());
        tariff::test::assert_parse_report(warnings.unexpected_fields(), parse_expect);
    }

    let tariff = T::from_json(tariff_elem.as_element()).unwrap();
    let (_tariff, warnings) = tariff.into_parts();
    drop(tariff_elem);

    let from_json_expect = test::parse_expect_json(expect_json.as_deref());
    tariff::test::assert_from_json_warnings(&warnings, from_json_expect);
}
