//! Direct peer-to-peer blob fetch end-to-end (peat#1013 expanded scope).
//!
//! Proves `NetworkedIrohBlobStore::fetch_blob_from_peer` works over real QUIC
//! with **zero** involvement of document sync — no `AutomergeBackend`, no
//! `SyncEngine`, no document ever created. Node B registers node A by hex
//! endpoint id only (`add_peer_from_hex_id`, relay/discovery-resolved — no
//! static address) and pulls a known hash directly from it.
//!
//! Runs real QUIC over loopback, so (like the sibling blob/distribution e2e
//! tests) it is gated to `automerge-backend` and exercised on the self-hosted
//! CI runner; it is contention-flaky on shared hosted runners.

#![cfg(feature = "automerge-backend")]

use peat_mesh::storage::{BlobMetadata, BlobStore, NetworkedIrohBlobStore};
use std::net::SocketAddr;
use tempfile::TempDir;

#[tokio::test]
async fn direct_fetch_from_peer_bypasses_document_sync() {
    let dir_a = TempDir::new().unwrap();
    let dir_b = TempDir::new().unwrap();
    let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();

    let store_a = NetworkedIrohBlobStore::bind(dir_a.path().join("blobs"), addr)
        .await
        .expect("bind A");
    let store_b = NetworkedIrohBlobStore::bind(dir_b.path().join("blobs"), addr)
        .await
        .expect("bind B");

    // B learns how to reach A's address (loopback test harness stand-in for
    // real discovery), then registers A by id only — no explicit socket
    // address is passed to the registration call itself, proving id-only
    // registration is sufficient once the address is resolvable.
    store_b
        .memory_lookup()
        .add_endpoint_info(store_a.endpoint().addr());
    let a_id_hex = hex::encode(store_a.endpoint_id().as_bytes());
    store_b
        .add_peer_from_hex_id(&a_id_hex)
        .await
        .expect("B registers A by id");

    // A creates a blob. No document, no backend, no sync engine exists
    // anywhere in this test — this is the entire "mesh sync" surface this
    // test deliberately does not touch.
    let data = b"direct P2P transfer, independent of document sync";
    let token = store_a
        .create_blob_from_bytes(data, BlobMetadata::with_name("direct-e2e.bin"))
        .await
        .expect("A creates blob");

    // B pulls directly from A by hex id.
    let handle = store_b
        .fetch_blob_from_peer(&token, &a_id_hex, |_| {})
        .await
        .expect("B fetches directly from A");

    assert_eq!(
        std::fs::read(&handle.path).expect("read fetched blob"),
        data
    );

    let _ = store_a.shutdown().await;
    let _ = store_b.shutdown().await;
}
