use rpki::data_model::ta::TrustAnchor;
use rpki::data_model::tal::Tal;
use rpki::fetch::http::{BlockingHttpFetcher, HttpFetcherConfig};
use rpki::validation::ca_instance::ca_instance_uris_from_ca_certificate;
use rpki::validation::from_tal::discover_root_ca_instance_from_tal_url;

const APNIC_TAL_URL: &str = "https://tal.apnic.net/tal-archive/apnic-rfc7730-https.tal";

#[test]
#[ignore = "live network smoke test (APNIC TAL)"]
fn apnic_tal_downloads_and_binds_to_ta_certificate() {
    let fetcher = BlockingHttpFetcher::new(HttpFetcherConfig::default()).expect("build fetcher");

    let tal_bytes = fetcher.fetch_bytes(APNIC_TAL_URL).expect("download TAL");
    let tal = Tal::decode_bytes(&tal_bytes).expect("decode TAL");

    let ta_uri = tal.ta_uris.first().expect("TAL has TA URIs").clone();
    let ta_bytes = fetcher
        .fetch_bytes(ta_uri.as_str())
        .expect("download TA cert");

    let trust_anchor = TrustAnchor::bind_der(tal, &ta_bytes, Some(&ta_uri)).expect("bind");

    let ca_uris = ca_instance_uris_from_ca_certificate(&trust_anchor.ta_certificate.rc_ca)
        .expect("extract CA instance URIs");
    assert!(ca_uris.rsync_base_uri.starts_with("rsync://"));
    assert!(ca_uris.manifest_rsync_uri.starts_with("rsync://"));
}

#[test]
#[ignore = "live network smoke test (APNIC TAL)"]
fn apnic_tal_discovery_api_smoke() {
    let fetcher = BlockingHttpFetcher::new(HttpFetcherConfig::default()).expect("build fetcher");
    let d = discover_root_ca_instance_from_tal_url(&fetcher, APNIC_TAL_URL).expect("discover");
    assert!(d.ca_instance.rsync_base_uri.starts_with("rsync://"));
    assert!(d.ca_instance.manifest_rsync_uri.starts_with("rsync://"));
}
