class TurnsController < ApplicationController
  before_action :require_login
  before_action :set_turn, only: %i[ show edit update destroy submit_orders process_turn ]

  # GET /turns or /turns.json
  def index
    @turns = Turn.all
  end

  # GET /turns/1 or /turns/1.json
  def show
  end

  # GET /turns/new
  def new
    @turn = Turn.new
  end

  # GET /turns/1/edit
  def edit
  end

  # POST /turns or /turns.json
  def create
    @turn = Turn.new(turn_params)

    respond_to do |format|
      if @turn.save
        format.html { redirect_to @turn, notice: "Turn was successfully created." }
        format.json { render :show, status: :created, location: @turn }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @turn.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /turns/1 or /turns/1.json
  def update
    respond_to do |format|
      if @turn.update(turn_params)
        format.html { redirect_to @turn, notice: "Turn was successfully updated.", status: :see_other }
        format.json { render :show, status: :ok, location: @turn }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @turn.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /turns/1 or /turns/1.json
  def destroy
    @turn.destroy!

    respond_to do |format|
      format.html { redirect_to turns_path, notice: "Turn was successfully destroyed.", status: :see_other }
      format.json { head :no_content }
    end
  end

  # PATCH /turns/1/submit_orders
  def submit_orders
    @turn = Turn.find(params[:id])
    power = params[:power]
    orders = params[:orders]&.permit!&.to_h || {}

    service = OrderSubmissionService.new(@turn, current_user)
    result = service.submit(power: power, orders: orders)

    if result[:success]
      redirect_to game_path(@turn.game), notice: result[:message]
    else
      redirect_to game_path(@turn.game), alert: result[:message]
    end
  end

  # POST /turns/1/process_turn
  def process_turn
    @turn = Turn.find(params[:id])
    @game = @turn.game

    # Check admin/turn ending permissions
    unless @game.solo_mode? || current_user&.admin? || @game.administrator == current_user
      redirect_to game_path(@game), alert: "ゲーム管理者のみターンを終了できます"
      return
    end

    service = TurnProcessingService.new(@turn)
    result = service.process(force: params[:force])

    if result[:success]
      redirect_to game_path(@game), notice: result[:message]
    else
      redirect_to game_path(@game), alert: result[:message]
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_turn
      @turn = Turn.find(params.expect(:id))
    end

    # Only allow a list of trusted parameters through.
    def turn_params
      params.expect(turn: [ :number, :phase, :game_state, :svg_date, :game_id, :possible_orders, :orders ])
    end
end
