import { Command } from './command';
import { GameData } from './gameData';
import { GameState } from './gameState';

export const GameRules = {
	step(state: GameState, data: GameData): GameState {
		const nextTick = state.tick + 1;

		// Get all commands for this step
		const commands = state.commandHistory.filter(
			(c) => c.step === nextTick
		);
		// Clone and update
		const newState: GameState = {
			...state,
			tick: state.tick + 1,
			units: state.units.map((u) => ({
				...u,
				x: u.x + 1, // Simple movement
			})),
		};
		for (const cmd of commands) {
			this.applyCommand(newState, cmd, data);
		}
		return newState;
	},

	applyCommand(state: GameState, cmd: Command, data: GameData): void {
		if (cmd.type === 'move') {
			const unit = state.units.find((u) => u.id === cmd.payload.id);
			if (unit) {
                unit.x += cmd.payload.dx * data.unitSpeed;
                unit.y += cmd.payload.dy * data.unitSpeed;
			}
		}
	},
};
