#!/usr/bin/env bats
#
# Group auto-selection. When neither --group nor TMUX_PARTY_GROUP names
# a group, cmd_host walks PARTY_GROUP_CANDIDATES and gates on the first
# group the caller belongs to; 'party' is the last candidate, a
# fallback rather than a hardcoded default.

load 'helpers'

setup() {
  setup_party_sandbox
  load_party_lib
}

teardown() { teardown_party_sandbox; }

# Put a stub id(1) on PATH whose -nG answer is $1; every other
# invocation falls through to the real id.
stub_id_groups() {
  mkdir -p "$PARTY_TMP/bin"
  real_id=$(command -v id)
  { printf '#!/bin/sh\n'
    printf 'case "$1" in\n'
    printf '  -nG) echo "%s" ;;\n' "$1"
    printf '  *) exec %s "$@" ;;\n' "$real_id"
    printf 'esac\n'
  } > "$PARTY_TMP/bin/id"
  chmod +x "$PARTY_TMP/bin/id"
  PATH="$PARTY_TMP/bin:$PATH"
}

@test "pick_host_group prefers staff over the party fallback" {
  stub_id_groups "$USER staff party"
  [ "$(pick_host_group)" = staff ]
}

@test "pick_host_group walks candidates in order: users beats wheel" {
  stub_id_groups "wheel users"
  [ "$(pick_host_group)" = users ]
}

@test "pick_host_group falls back to party" {
  stub_id_groups "$USER dialout party"
  [ "$(pick_host_group)" = party ]
}

@test "pick_host_group fails when the caller is in no candidate" {
  stub_id_groups "$USER dialout"
  run pick_host_group
  [ "$status" -ne 0 ]
  [ -z "$output" ]
}

@test "PARTY_GROUP_CANDIDATES env overrides the candidate list" {
  stub_id_groups "$USER randomgrp"
  PARTY_GROUP_CANDIDATES="randomgrp party" \
    run pick_host_group
  [ "$output" = randomgrp ]
}

@test "host auto-selects the caller's group, announces it, records it" {
  unset TMUX_PARTY_GROUP
  export PARTY_GROUP_CANDIDATES="$(id -gn) party"
  run "$PARTY_BIN" host autosel
  [ "$status" -eq 0 ]
  [[ "$output" == *"gating on group '$(id -gn)'"* ]]
  grep -qx "GROUP=$(id -gn)" \
    "$PARTY_SOCKET_DIR/party-$USER:autosel.d/roster"
}

@test "explicit TMUX_PARTY_GROUP disables auto-selection" {
  export TMUX_PARTY_GROUP="$(id -gn)"
  run "$PARTY_BIN" host explicit-env
  [ "$status" -eq 0 ]
  [[ "$output" != *"auto-selected"* ]]
}

@test "host in no candidate group gets the remediation message" {
  unset TMUX_PARTY_GROUP
  export PARTY_GROUP_CANDIDATES="no-such-group-xyzzy"
  run "$PARTY_BIN" host nogroup
  [ "$status" -eq 1 ]
  [[ "$output" == *"not in the 'party' group"* ]]
  [[ "$output" == *"--group"* ]]
}
