use donion::git::{self, RemoteRef};
use tempfile::TempDir;

#[test]
fn parse_full_shas() {
    let output = "\
abc123def456789012345678901234567890abcd\trefs/heads/main\n\
def456abc789012345678901234567890abcd1234\trefs/heads/feature/foo\n\
111222333444555666777888999000aaabbbcccddd\trefs/tags/v1.0.0\n";

    let refs = git::parse_ls_remote(output);
    assert_eq!(refs.len(), 3);
    assert_eq!(refs[0].sha, "abc123def456789012345678901234567890abcd");
    assert_eq!(refs[0].name, "refs/heads/main");
    assert_eq!(refs[1].name, "refs/heads/feature/foo");
    assert_eq!(refs[2].name, "refs/tags/v1.0.0");
}

#[test]
fn parse_empty() {
    assert!(git::parse_ls_remote("").is_empty());
}

#[test]
fn parse_ignores_malformed_lines() {
    let output = "no-tab-here\nabc123\trefs/heads/main\n";
    let refs = git::parse_ls_remote(output);
    assert_eq!(refs.len(), 1);
    assert_eq!(refs[0].name, "refs/heads/main");
}

#[test]
fn refs_by_branch_filters_heads_only() {
    let refs = vec![
        RemoteRef { sha: "aaa".into(), name: "refs/heads/main".into() },
        RemoteRef { sha: "bbb".into(), name: "refs/heads/dev".into() },
        RemoteRef { sha: "ccc".into(), name: "refs/tags/v1".into() },
    ];

    let map = git::refs_by_branch(&refs);
    assert_eq!(map.len(), 2);
    assert_eq!(map["main"], "aaa");
    assert_eq!(map["dev"], "bbb");
    assert!(!map.contains_key("v1"));
}

#[test]
fn parse_handles_tags_and_head() {
    let input = "\
0000000000000000000000000000000000000000\tHEAD\n\
aaaa\trefs/heads/main\n\
bbbb\trefs/tags/v1.0\n\
cccc\trefs/pull/1/head\n";

    let refs = git::parse_ls_remote(input);
    let by_branch = git::refs_by_branch(&refs);

    assert_eq!(by_branch.len(), 1);
    assert_eq!(by_branch["main"], "aaaa");
}

#[test]
fn parse_roundtrip() {
    let input = "abc123\trefs/heads/main\ndef456\trefs/heads/dev\n";
    let refs = git::parse_ls_remote(input);
    let by_branch = git::refs_by_branch(&refs);

    assert_eq!(by_branch["main"], "abc123");
    assert_eq!(by_branch["dev"], "def456");
}

#[tokio::test]
async fn ls_remote_fails_on_non_git_dir() {
    let tmp = TempDir::new().unwrap();
    let result = git::ls_remote(tmp.path()).await;
    assert!(result.is_err());
}
