SetStatusBattleMutationInterceptor.kt

package io.github.lishangbu.avalon.game.battle.engine.core.runtime.flow

import io.github.lishangbu.avalon.game.battle.engine.core.constant.BattleAttributeKeys
import io.github.lishangbu.avalon.game.battle.engine.core.event.StandardHookNames
import io.github.lishangbu.avalon.game.battle.engine.core.mutation.BattleMutation
import io.github.lishangbu.avalon.game.battle.engine.core.mutation.SetStatusMutation
import io.github.lishangbu.avalon.game.battle.engine.core.runtime.support.MutationTargetSelectorResolver

/**
 * 主状态附加 mutation 拦截器。
 */
class SetStatusBattleMutationInterceptor : BattleMutationInterceptor {
    /**
     * 当前拦截器在链中的执行顺序。
     */
    override val order: Int = 0

    /**
     * 判断当前拦截器是否负责处理给定 mutation。
     */
    override fun supports(mutation: BattleMutation): Boolean = mutation is SetStatusMutation

    /**
     * 拦截主状态附加 mutation。
     */
    override fun intercept(
        context: BattleMutationInterceptionContext,
        attachedEffectProcessor: BattleAttachedEffectProcessor,
    ): BattleMutationInterceptionResult {
        val mutation =
            context.mutation as? SetStatusMutation
                ?: return BattleMutationInterceptionResult(context.snapshot, true, context.mutation)
        val targetUnitIds =
            MutationTargetSelectorResolver.resolve(
                mutation.target,
                BattleMutationInterceptorSupport.mutationApplicationContext(context),
            )
        var currentSnapshot = context.snapshot
        var blocked = false

        targetUnitIds.forEach { affectedTargetId ->
            val result =
                attachedEffectProcessor.process(
                    snapshot = currentSnapshot,
                    unitId = affectedTargetId,
                    hookName = StandardHookNames.ON_SET_STATUS.value,
                    targetId = affectedTargetId,
                    sourceId = context.sourceId,
                    relay = true,
                    attributes =
                        buildMap {
                            put("statusEffectId", mutation.statusEffectId)
                            BattleMutationInterceptorSupport
                                .resolveTargetRelation(currentSnapshot, context.sourceId, affectedTargetId)
                                ?.let { relation -> put(BattleAttributeKeys.TARGET_RELATION, relation) }
                        },
                )
            currentSnapshot = result.snapshot
            if (result.cancelled || result.relay == false) {
                blocked = true
            }
        }

        return BattleMutationInterceptionResult(
            snapshot = currentSnapshot,
            allowed = !blocked,
            mutation = mutation,
        )
    }
}