package thb.jeanluc.adventure.command.impl;

import lombok.RequiredArgsConstructor;
import thb.jeanluc.adventure.command.Command;
import thb.jeanluc.adventure.game.Game;
import thb.jeanluc.adventure.game.GameContext;
import thb.jeanluc.adventure.save.SaveException;
import thb.jeanluc.adventure.save.SaveService;

import java.util.List;

/**
 * Saves the active slot and returns to the main menu by stopping the loop.
 * Usage: {@code menu} (aliases {@code quit}, {@code exit}).
 */
@RequiredArgsConstructor
public class MenuCommand implements Command {

    private final SaveService saves;
    private Game game;

    /** Binds the running game (two-phase wiring, as the registry is built first). */
    public void bind(Game game) {
        this.game = game;
    }

    @Override
    public void execute(GameContext ctx, List<String> args) {
        try {
            saves.save(ctx.getSession());
            ctx.getIo().write("Game saved. Returning to the main menu.");
        } catch (SaveException e) {
            ctx.getIo().write("Could not save: " + e.getUserMessage());
        }
        if (game != null) {
            game.stop();
        }
    }

    @Override
    public String help() {
        return "menu  -  save and return to the main menu (aliases: quit, exit)";
    }
}
