use akira_billing::platform::{download_url, pick_download_url, Arch, Os, Platform};

#[test]
fn slug_joins_os_and_arch() {
    let p = Platform {
        os: Os::Macos,
        arch: Arch::Arm64,
    };
    assert_eq!(p.slug(), "macos-arm64");

    let p = Platform {
        os: Os::Linux,
        arch: Arch::X86_64,
    };
    assert_eq!(p.slug(), "linux-x86_64");

    let p = Platform {
        os: Os::Windows,
        arch: Arch::X86_64,
    };
    assert_eq!(p.slug(), "windows-x86_64");
}

#[test]
fn os_from_target_accepts_normalized() {
    assert_eq!(Os::from_target("macos"), Some(Os::Macos));
    assert_eq!(Os::from_target("linux"), Some(Os::Linux));
    assert_eq!(Os::from_target("windows"), Some(Os::Windows));
    assert_eq!(Os::from_target("haiku"), None);
}

#[test]
fn arch_from_target_normalizes_aliases() {
    assert_eq!(Arch::from_target("aarch64"), Some(Arch::Arm64));
    assert_eq!(Arch::from_target("arm64"), Some(Arch::Arm64));
    assert_eq!(Arch::from_target("x86_64"), Some(Arch::X86_64));
    assert_eq!(Arch::from_target("amd64"), Some(Arch::X86_64));
    assert_eq!(Arch::from_target("riscv"), None);
}

#[test]
fn detect_returns_some_on_supported_targets() {
    let detected = Platform::detect();
    assert!(detected.is_some(), "detect() should match host target");
}

#[test]
fn predicates_match_os() {
    let mac = Platform {
        os: Os::Macos,
        arch: Arch::Arm64,
    };
    let lin = Platform {
        os: Os::Linux,
        arch: Arch::X86_64,
    };
    let win = Platform {
        os: Os::Windows,
        arch: Arch::X86_64,
    };

    assert!(mac.is_macos() && !mac.is_linux() && !mac.is_windows());
    assert!(lin.is_linux() && !lin.is_macos());
    assert!(win.is_windows() && !win.is_linux());
}

#[test]
fn download_url_builds_canonical_path() {
    let p = Platform {
        os: Os::Macos,
        arch: Arch::Arm64,
    };
    assert_eq!(
        download_url("https://billing.test", "unified-dev", "stable", &p),
        "https://billing.test/api/v1/downloads/unified-dev/stable/macos-arm64"
    );

    assert_eq!(
        download_url("https://billing.test/", "unified-dev", "stable", &p),
        "https://billing.test/api/v1/downloads/unified-dev/stable/macos-arm64"
    );
}

#[test]
fn pick_download_url_uses_fallback_when_detect_supports_host() {
    let result = pick_download_url("https://billing.test", "unified-dev", "stable", None);
    assert!(result.is_some());
}

#[test]
fn pick_download_url_falls_back_when_provided() {
    let fallback = Some(Platform {
        os: Os::Linux,
        arch: Arch::X86_64,
    });
    let url = pick_download_url("https://billing.test", "unified-dev", "stable", fallback)
        .expect("fallback should yield a url");
    assert!(
        url.ends_with("/macos-arm64")
            || url.ends_with("/linux-x86_64")
            || url.ends_with("/windows-x86_64")
    );
}
