#!/usr/bin/env bats

load 'helpers'

setup() {
  setup_party_sandbox
  require_party_group     # need real group membership for chgrp
}

teardown() { teardown_party_sandbox; }

# Per-party roster path: ${PARTY_SOCKET_DIR}/party-${USER}:${NAME}.d/roster.
party_rec() { printf '%s/party-%s:%s.d/roster\n' "$PARTY_SOCKET_DIR" "$USER" "$1"; }

@test "party host <name> creates a roster record and a live tmux server" {
  run "$PARTY_BIN" host smoke
  [ "$status" -eq 0 ]
  [[ "$output" == *"smoke"* ]]
  rec=$(party_rec smoke)
  [ -f "$rec" ]
  grep -q "^PARTY_NAME=smoke$"    "$rec"
  grep -q "^HOST_USER=$USER$"     "$rec"
  ! grep -q "^MODE="              "$rec"
  ! grep -q "^OPS="               "$rec"
  pid=$(awk -F= '$1=="SERVER_PID"{print $2}' "$rec")
  kill -0 "$pid"
  sock=$(awk -F= '$1=="SOCKET"{print $2}' "$rec")
  [ -S "$sock" ]
  tmux -S "$sock" has-session -t smoke
}

@test "party host enforces unique party name" {
  "$PARTY_BIN" host dupe
  run "$PARTY_BIN" host dupe
  [ "$status" -ne 0 ]
  [[ "$output" == *"already running"* ]]
}

@test "party host rejects bad names" {
  run "$PARTY_BIN" host "../escape"
  [ "$status" -ne 0 ]
}

@test "party host without name uses a default" {
  run "$PARTY_BIN" host
  [ "$status" -eq 0 ]
  ls -d "$PARTY_SOCKET_DIR"/party-"$USER":*.d >/dev/null
}

@test "party host puts host on access list with write" {
  "$PARTY_BIN" host acl
  rec=$(party_rec acl)
  sock=$(awk -F= '$1=="SOCKET"{print $2}' "$rec")
  tmux -S "$sock" server-access -l | grep -q "^$USER"
}

@test "party close kills the server and removes the roster record" {
  "$PARTY_BIN" host clo
  rec=$(party_rec clo)
  sock=$(awk -F= '$1=="SOCKET"{print $2}' "$rec")
  pid=$(awk -F= '$1=="SERVER_PID"{print $2}' "$rec")

  run "$PARTY_BIN" close clo
  [ "$status" -eq 0 ]
  [ ! -f "$rec" ]
  ! kill -0 "$pid" 2>/dev/null
  [ ! -S "$sock" ]
}

@test "party close rejects bad names" {
  # Previous incarnation of this test edited HOST_USER in the roster
  # file and expected close to refuse. That's no longer the trust
  # model — host identity is anchored on dir ownership, not file
  # content (commit 94befac), so editing HOST_USER is a no-op.
  # The "not the host" path now tests as: another user owns the dir,
  # which we can't fake without root. Coverage for the symlink and
  # forged-field cases lives in tests/95-stub-roundtrip.bats. What we
  # add here is parity with `party host rejects bad names`: cmd_close
  # validates the name before any path or filesystem work.
  run "$PARTY_BIN" close "../escape"
  [ "$status" -ne 0 ]
}

@test "party host puts only the host on the access list (no auto-population)" {
  "$PARTY_BIN" host inv
  rec=$(party_rec inv)
  sock=$(awk -F= '$1=="SOCKET"{print $2}' "$rec")
  count=$(tmux -S "$sock" server-access -l | wc -l)
  [ "$count" -eq 1 ]
  "$PARTY_BIN" close inv
}

