use super::{
    STREAM_CTRL_SIZE_11, STREAM_CTRL_SIZE_15, UvcConfig, adjust_length,
    build_streaming_control, compute_payload_cap, read_le32, stream_ctrl_len,
};
use serial_test::serial;
use temp_env::with_var;

#[test]
#[serial]
fn stream_ctrl_len_falls_back_on_invalid_env() {
    with_var("LESAVKA_UVC_CTRL_LEN", Some("bogus"), || {
        assert_eq!(stream_ctrl_len(), STREAM_CTRL_SIZE_11);
    });
    with_var("LESAVKA_UVC_CTRL_LEN", Some("34"), || {
        assert_eq!(stream_ctrl_len(), STREAM_CTRL_SIZE_15);
    });
}

#[test]
fn adjust_length_pads_and_truncates() {
    assert_eq!(adjust_length(vec![1, 2, 3], 2), vec![1, 2]);
    assert_eq!(adjust_length(vec![1, 2], 4), vec![1, 2, 0, 0]);
}

#[test]
fn build_streaming_control_sets_interval_frame_size_and_payload() {
    let cfg = UvcConfig {
        width: 1280,
        height: 720,
        fps: 25,
        interval: 400_000,
        max_packet: 512,
        frame_size: 1234,
    };
    let control = build_streaming_control(&cfg, STREAM_CTRL_SIZE_15);
    assert_eq!(control[2], 1);
    assert_eq!(read_le32(&control, 4), 400_000);
    assert_eq!(read_le32(&control, 18), 1234);
    assert_eq!(read_le32(&control, 22), 512);
}

#[test]
#[serial]
fn compute_payload_cap_honors_explicit_override() {
    with_var("LESAVKA_UVC_MAXPAYLOAD_LIMIT", Some("333"), || {
        let cap = compute_payload_cap(false).expect("env override should win");
        assert_eq!(cap.limit, 333);
        assert_eq!(cap.source, "env");
    });
}
