import { Component } from "../core/world";
import type { RPGVariables } from "../types";
import { action, component } from "../utils/decorators";

interface Var {
    key: string;
    value: RPGVariables[string];
}

/**
 * Generic runtime key-value store set by dialog actions, quest scripts, and game events —
 * values whose keys are only known at runtime or come from data files.
 *
 * Prefer a typed `Component<TState>` when the shape is fixed at compile time
 * (e.g. health, stats, slot definitions).
 */
@component
export class Variables extends Component<RPGVariables> {
    constructor() {
        super({});
    }

    override getVariables() {
        return this.state;
    }

    @action
    set({ key, value }: Var) {
        const prev = this.state[key];
        this.state[key] = value;
        this.emit('set', { key, value, prev });
    }

    @action
    unset(key: string) {
        const prev = this.state[key];
        delete this.state[key];
        this.emit('unset', { key, prev });
    }

    @action
    update({ key, value }: Var) {
        const currentValue = this.state[key] ?? 0;
        if (typeof currentValue === 'number' && typeof value === 'number') {
            this.set({ key, value: currentValue + value });
        } else {
            console.warn(`[Variables] increment failed: ${key} is not a number`);
        }
        return this.state.vars;
    }
}
