import type { GeneralTriggerState } from '@sammo-ts/logic/domain/entities.js';
import type { Constraint, ConstraintContext } from '@sammo-ts/logic/constraints/types.js';
import type { GeneralActionDefinition } from '@sammo-ts/logic/actions/definition.js';
import type { GeneralActionOutcome, GeneralActionResolveContext } from '@sammo-ts/logic/actions/engine.js';
import type { TurnCommandEnv } from '@sammo-ts/logic/actions/turn/commandEnv.js';
import { defaultActionContextBuilder } from '@sammo-ts/logic/actions/turn/actionContext.js';
import type { GeneralTurnCommandSpec } from './index.js';
import { GeneralActionPipeline } from '@sammo-ts/logic/actionModules/general.js';

export interface RecoveryArgs {}

export interface RecoveryEnvironment {
    injuryDelta?: number;
    costGold?: number;
}

const ACTION_NAME = '요양';

export class ActionDefinition<
    TriggerState extends GeneralTriggerState = GeneralTriggerState,
> implements GeneralActionDefinition<TriggerState, RecoveryArgs> {
    public readonly key = 'che_요양';
    public readonly name = ACTION_NAME;
    private readonly env: RecoveryEnvironment;
    private readonly pipeline: GeneralActionPipeline<TriggerState>;

    constructor(env: RecoveryEnvironment & Partial<Pick<TurnCommandEnv, 'generalActionModules'>> = {}) {
        this.env = env;
        this.pipeline = new GeneralActionPipeline(env.generalActionModules ?? []);
    }

    parseArgs(_raw: unknown): RecoveryArgs | null {
        void _raw;
        return {};
    }

    buildConstraints(_ctx: ConstraintContext, _args: RecoveryArgs): Constraint[] {
        return [];
    }

    resolve(
        context: GeneralActionResolveContext<TriggerState>,
        _args: RecoveryArgs
    ): GeneralActionOutcome<TriggerState> {
        const general = context.general;
        const nextInjury = 0;
        const costGold = this.env.costGold ?? 0;

        // 직접 수정 (Immer Draft)
        general.injury = nextInjury;
        general.gold = Math.max(0, general.gold - costGold);
        general.experience += this.pipeline.onCalcStat(context, 'experience', 10);
        general.dedication += this.pipeline.onCalcStat(context, 'dedication', 7);

        context.addLog(`건강 회복을 위해 요양합니다.`);

        return { effects: [] };
    }
}

// 예약 턴 실행은 기본 컨텍스트만 사용한다.
export const actionContextBuilder = defaultActionContextBuilder;

export const commandSpec: GeneralTurnCommandSpec = {
    key: 'che_요양',
    category: '개인',
    reqArg: false,

    createDefinition: (env: TurnCommandEnv) => new ActionDefinition(env),
};
