use std::collections::BTreeMap;
use trazaeo::telemetry::{
    make_audit_record, make_event, make_metric, make_span, TelemetryBuffer, TelemetryEvent,
};

/// Tests that telemetry integration emits trace metric and audit records for publish flow.
#[test]
fn telemetry_integration_emits_trace_metric_and_audit_records_for_publish_flow() {
    let mut telemetry = TelemetryBuffer::default();
    let trace_id = "trace-2026-01-01-1";
    let run_id = "run-publish-1";
    let subject_id = "publish-1";

    telemetry.start_span(make_span(
        trace_id,
        run_id,
        "S5",
        subject_id,
        "2026-01-01T00:20:00Z",
    ));

    let mut attrs = BTreeMap::new();
    attrs.insert("trace_id".to_string(), trace_id.to_string());
    attrs.insert("run_id".to_string(), run_id.to_string());
    attrs.insert("dataset_id".to_string(), "sst".to_string());
    telemetry.push(TelemetryEvent {
        stage: "S5".to_string(),
        subject_id: subject_id.to_string(),
        status: "ok".to_string(),
        attrs,
    });
    telemetry.push(make_event("S6", subject_id, "ok"));

    telemetry.record_metric(make_metric(
        "verification_latency_ms",
        "S6",
        subject_id,
        17.2,
        "ms",
        "2026-01-01T00:21:00Z",
    ));
    telemetry.record_audit(make_audit_record(
        "actor-1",
        "publish",
        subject_id,
        "2026-01-01T00:21:05Z",
        "publish://1",
    ));
    assert!(telemetry.end_span(trace_id, "S5", "2026-01-01T00:21:10Z", "ok"));

    assert_eq!(telemetry.query_by_subject(subject_id).len(), 2);
    assert_eq!(
        telemetry
            .query_metric("verification_latency_ms", "S6")
            .len(),
        1
    );
    assert_eq!(telemetry.query_trace(trace_id).len(), 1);
    assert_eq!(
        telemetry
            .query_audit(Some("actor-1"), Some("publish"), None, None)
            .len(),
        1
    );
}
