//! Integration tests for manifest error surfaces and link-header discovery.

use index_dom::{
    IndexManifestError, discover_index_manifest_link_from_http_link_header,
    well_known_index_manifest_url,
};

#[test]
fn index_manifest_error_display_messages_are_actionable() {
    let errors = vec![
        IndexManifestError::TooLarge {
            max_bytes: 4096,
            actual_bytes: 9000,
        },
        IndexManifestError::InvalidJson("trailing comma".to_owned()),
        IndexManifestError::UnsupportedVersion("index.idx/v0".to_owned()),
        IndexManifestError::InvalidSourceUrl("not a url".to_owned()),
        IndexManifestError::InvalidPageUrl("://bad".to_owned()),
        IndexManifestError::CrossOrigin {
            source_url: "https://other.example/.well-known/index.idx".to_owned(),
            page_url: "https://example.org/docs".to_owned(),
        },
        IndexManifestError::InvalidScope("scope".to_owned()),
        IndexManifestError::OutOfScope {
            scope: "/docs".to_owned(),
            page_path: "/blog/post".to_owned(),
        },
        IndexManifestError::TooManyHints {
            kind: "fields",
            max: 16,
        },
        IndexManifestError::InvalidHint {
            kind: "date",
            reason: "unsupported style".to_owned(),
        },
    ];

    for error in errors {
        let rendered = error.to_string();
        assert!(!rendered.trim().is_empty());
        assert!(!rendered.contains('\n'));
    }
}

#[test]
fn manifest_link_header_discovery_skips_malformed_and_accepts_external_target() {
    let page_url = "https://example.org/docs/page";
    let malformed =
        discover_index_manifest_link_from_http_link_header("not-a-link-header", page_url);
    assert!(malformed.is_none());

    let external = discover_index_manifest_link_from_http_link_header(
        "<https://other.example/.well-known/index.idx>; rel=\"index-manifest\"",
        page_url,
    );
    assert_eq!(
        external.as_deref(),
        Some("https://other.example/.well-known/index.idx")
    );
}

#[test]
fn well_known_manifest_url_requires_absolute_page_url() {
    assert!(well_known_index_manifest_url("not a url").is_none());
    assert_eq!(
        well_known_index_manifest_url("https://example.org/docs/page").as_deref(),
        Some("https://example.org/.well-known/index.idx")
    );
}
