#!/usr/bin/env bats
# Tests for scripts/lib/orca-log.sh (C-17 — slog-compatible JSON to syslog).
# Verifies the JSON structure is valid, field set is present, level maps correctly,
# and the logger-fallback-to-stderr path works in test environments (no logger).

load test_helper

@test "orca_log_info emits valid JSON with all required fields" {
	export ORCA_LOG_ACTOR="test-actor"
	output="$(_orca_log_for_test info test-action test-resource ok "")"
	assert_json_field "$output" "ts"
	assert_json_field "$output" "level"
	assert_json_field "$output" "actor"
	assert_json_field "$output" "action"
	assert_json_field "$output" "resource"
	assert_json_field "$output" "result"
	assert_contains "$output" '"level":"info"'
	assert_contains "$output" '"action":"test-action"'
	assert_contains "$output" '"resource":"test-resource"'
	assert_contains "$output" '"result":"ok"'
}

@test "orca_log_warn maps level correctly" {
	output="$(_orca_log_for_test warn w-action w-resource warn-result)"
	assert_contains "$output" '"level":"warn"'
}

@test "orca_log_error maps level and includes error field when provided" {
	output="$(_orca_log_for_test error err-action err-resource failed "something broke")"
	assert_contains "$output" '"level":"error"'
	assert_contains "$output" '"result":"failed"'
	assert_contains "$output" '"error":"something broke"'
}

@test "orca_log_error omits error field when not provided" {
	output="$(_orca_log_for_test error err-action err-resource failed)"
	assert_contains "$output" '"level":"error"'
	assert_not_contains "$output" '"error":'
}

@test "orca_log escapes quotes and backslashes in error field" {
	output="$(_orca_log_for_test error a r failed 'has "quote" and \backslash')"
	assert_contains "$output" '\"quote\"'
	assert_contains "$output" '\\backslash'
}

@test "ORCA_LOG_ACTOR env var overrides the actor field" {
	export ORCA_LOG_ACTOR="custom-actor-123"
	output="$(_orca_log_for_test info a r ok)"
	assert_contains "$output" '"actor":"custom-actor-123"'
}

# Test helper: source orca-log.sh and emit to stderr (force fallback by hiding logger).
_orca_log_for_test() {
	local level="$1" action="$2" resource="$3" result="$4" error="${5:-}"
	# Source the library in a subshell with logger hidden so it falls back to stderr.
	(
		PATH="/usr/bin:/bin"  # hide logger if it's in /usr/local/bin etc.
		# shellcheck disable=SC2317 # logger is overridden below for test capture
		logger() { echo "$3"; }  # $3 is the message arg (logger -t orca "$line")
		# shellcheck disable=SC1091 # path is set at runtime by SCRIPTS_DIR
		source "$SCRIPTS_DIR/lib/orca-log.sh"
		case "$level" in
			info)  orca_log_info  "$action" "$resource" "$result" "$error" ;;
			warn)  orca_log_warn  "$action" "$resource" "$result" "$error" ;;
			error) orca_log_error "$action" "$resource" "$result" "$error" ;;
		esac
	)
}