#!/usr/bin/env bash
# ============================================================================
# TC-27 — Active Effects
# Usage: ./tc-27-active-effects.sh [--navigate]
# ============================================================================
set -uo pipefail
source "$(dirname "$0")/tc-header.sh"

echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║   TC-27 — Active Effects                                    ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""

tc_ensure_ready

# Setup
SETUP=$(jse_get_async "
	const ex = game.actors.getName('TC-27 Test');
	if (ex) await ex.delete();
	const [actor] = await Actor.createDocuments([{
		type: 'personnage', name: 'TC-27 Test',
		system: {
			carac: { force: {value: 12} },
			sante: { vie: {value: 12, max: 12}, endurance: {value: 20, max: 20} }
		}
	}]);
	return { actorId: actor.id };
")
AID=$(eval_ok "$SETUP" actorId)

# ============================================================================
echo "--- TC-27-001: Création effet ---"
# ============================================================================
R=$(jse_get_async "
	try {
		const a = game.actors.get('$AID');
		if (!a) return {error: 'no actor'};
		const effect = await ActiveEffect.create({
			name: 'TC-27 Test Effect',
			changes: [{ key: 'system.sante.vie.value', mode: CONST.ACTIVE_EFFECT_MODES.ADD, value: 5 }],
		}, { parent: a });
		return { created: !!effect, id: effect?.id, name: effect?.name };
	} catch(e) { return {error: e.message}; }
")
CREATED=$(eval_ok "$R" created)
ERR=$(eval_ok "$R" error)
[ "$CREATED" = "True" ] && pass "TC-27-001: effet créé" || fail "TC-27-001: KO ($ERR)"

# ============================================================================
echo "--- TC-27-002: Application effet sur acteur ---"
# ============================================================================
R=$(jse_get_async "
	try {
		const a = game.actors.get('$AID');
		if (!a) return {error: 'no actor'};
		// Effect should have added 5 to vie.value — but ActiveEffect application
		// might compute differently. Just check the effect exists and is active.
		const hasEffect = a.effects.some(e => e.name === 'TC-27 Test Effect');
		const isActive = a.effects.some(e => e.name === 'TC-27 Test Effect' && !e.disabled);
		const vie = a.system.sante?.vie?.value;
		return { vie, hasEffect, isActive, applied: isActive };
	} catch(e) { return {error: e.message}; }
")
VIE=$(eval_ok "$R" vie)
APPLIED=$(eval_ok "$R" applied)
ERR=$(eval_ok "$R" error)
[ "$APPLIED" = "True" ] && pass "TC-27-002: vie = $VIE (effet appliqué)" || fail "TC-27-002: KO ($ERR)"

# ============================================================================
echo "--- TC-27-003: Suppression effet ---"
# ============================================================================
R=$(jse_get_async "
	try {
		const a = game.actors.get('$AID');
		if (!a) return {error: 'no actor'};
		const effect = a.effects.find(e => e.name === 'TC-27 Test Effect');
		if (!effect) return {error: 'no effect'};
		await effect.delete();
		await new Promise(r => setTimeout(r, 500));
		const vieAfter = a.system.sante?.vie?.value;
		const stillHas = a.effects.some(e => e.name === 'TC-27 Test Effect');
		return { vieAfter, stillHas, restored: !stillHas };
	} catch(e) { return {error: e.message}; }
")
RESTORED=$(eval_ok "$R" restored)
ERR=$(eval_ok "$R" error)
[ "$RESTORED" = "True" ] && pass "TC-27-003: effet supprimé, valeur restaurée" || fail "TC-27-003: KO ($ERR)"

# ============================================================================
echo "--- TC-27-004: Effets de statut ---"
# ============================================================================
R=$(jse_get_async "
	try {
		const effects = game.rdd?.statusEffects ?? CONFIG.statusEffects;
		return { count: effects?.length ?? 0, hasStatus: !!effects };
	} catch(e) { return {error: e.message}; }
")
COUNT=$(eval_ok "$R" count)
HASSTAT=$(eval_ok "$R" hasStatus)
ERR=$(eval_ok "$R" error)
[ "$HASSTAT" = "True" ] && pass "TC-27-004: statusEffects = $COUNT" || fail "TC-27-004: KO ($ERR)"

# ============================================================================
echo ""
echo "--- Cleanup ---"
CLEANUP=$(jse_get_async "
	const a = game.actors.getName('TC-27 Test');
	if (a) { await a.delete(); return 'deleted'; }
	return 'none';
" | tr -d '"\n')
[ "$CLEANUP" = "deleted" ] && pass "Cleanup: actor deleted" || fail "Cleanup: $CLEANUP"

echo ""
echo "--- Console errors ---"
ERRS=$(tc_console_errors)
[ "$ERRS" -le 5 ] 2>/dev/null && pass "Console errors ≤5 ($ERRS)" || fail "Console errors: $ERRS"

tc_summary