use std::time::Duration;

use dotenvy::dotenv;
use reqwest::blocking::Client;
use sunocore::validation::env::cdn_base_url_unwrap;
use uuid::Uuid;

// Integration test: fetch from <CDN_BASE_URL>/<clip_id>.mp3
// and ensure it returns valid mp3 data.
#[test]
fn fetch_cdn_mp3() {
    // Load .env for CDN_BASE_URL
    let _ = dotenv();

    let base = cdn_base_url_unwrap();

    // This clip ID is from a real staging project used in other tests
    let clip_id = "012ad0f4-d29d-4f5f-a141-83f11f94d114".to_string();

    let _expected_uuid = Uuid::parse_str(&clip_id).expect("clip_id must be a valid UUID");

    let url = format!("{}/{}.mp3", base.trim_end_matches('/'), clip_id);

    let client = Client::builder()
        .timeout(Duration::from_secs(30))
        .build()
        .expect("build http client");

    let resp = client
        .get(&url)
        .send()
        .unwrap_or_else(|e| panic!("request to {} failed: {}", url, e));

    assert!(
        resp.status().is_success(),
        "HTTP {} fetching {}. Is the CDN_BASE_URL correct?",
        resp.status(),
        url
    );

    // Read bytes
    let body = resp
        .bytes()
        .unwrap_or_else(|e| panic!("reading body from {} failed: {}", url, e));

    // Basic sanity checks for mp3 data
    assert!(body.len() > 0, "expected mp3 data to be non-empty");

    // Check for mp3 header (ID3 or MPEG frame sync)
    // MP3 files typically start with ID3 tag (0x49, 0x44, 0x33) or MPEG sync (0xFF, 0xFB/0xFA)
    assert!(body.len() >= 3, "mp3 file should be at least 3 bytes");

    let starts_with_id3 = body[0] == 0x49 && body[1] == 0x44 && body[2] == 0x33;
    let starts_with_mpeg = body[0] == 0xFF && (body[1] & 0xE0 == 0xE0);

    assert!(
        starts_with_id3 || starts_with_mpeg,
        "mp3 data should start with ID3 tag or MPEG sync marker"
    );
}
