#!/usr/bin/env bats

setup() {
    load 'test_helper/common_setup'
    _common_setup
}
teardown() {
    _common_teardown
}

@test "hk check fails on invalid config" {
    cd "$BATS_TEST_TMPDIR"

    # Create invalid pkl config
    cat > hk.pkl <<'EOF'
invalid pkl syntax content
EOF

    # hk check should fail with config error
    run hk check
    assert_failure
    assert_output --partial "Failed to load config"
    assert_output --partial "Invalid property definition"
}

@test "hk fix fails on invalid config" {
    cd "$BATS_TEST_TMPDIR"

    # Create invalid pkl config
    cat > hk.pkl <<'EOF'
this is not valid pkl
EOF

    # hk fix should fail with config error
    run hk fix
    assert_failure
    assert_output --partial "Failed to load config"
    assert_output --partial "expected identifier"
}

@test "hk run fails on invalid config" {
    cd "$BATS_TEST_TMPDIR"

    # Create invalid pkl config
    cat > hk.pkl <<'EOF'
broken config
EOF

    # hk run should fail with config error
    run hk run pre-commit
    assert_failure
    assert_output --partial "Failed to load config"
    assert_output --partial "Invalid property definition"
}

@test "hk config commands fail on invalid config" {
    cd "$BATS_TEST_TMPDIR"

    # Create invalid pkl config
    cat > hk.pkl <<'EOF'
not pkl format
EOF

    # config get should fail
    run hk config get jobs
    assert_failure
    assert_output --partial "Failed to load config"

    # config dump should fail
    run hk config dump
    assert_failure
    assert_output --partial "Failed to load config"

    # config explain should fail
    run hk config explain jobs
    assert_failure
    assert_output --partial "Failed to load config"
}

@test "hk util ignores invalid project and user config" {
    echo "clean line" > clean.txt

    cat > hk.pkl <<'EOF'
invalid project config
EOF

    run hk util trailing-whitespace clean.txt
    assert_success
    refute_output

    rm hk.pkl
    mkdir -p "$XDG_CONFIG_HOME/hk"
    cat > "$XDG_CONFIG_HOME/hk/config.pkl" <<'EOF'
invalid user config
EOF

    run hk util trailing-whitespace clean.txt
    assert_success
    refute_output
}


@test "config error shows helpful details" {
    cd "$BATS_TEST_TMPDIR"

    # Create config with specific syntax error
    cat > hk.pkl <<'EOF'
amends "pkl/Config.pkl"
invalid_field =
EOF

    # Should show the specific syntax error
    run hk check
    assert_failure
    assert_output --partial "unexpected token in expression"
}
