class Admin::Admissions::StatusesController < Admin::Admissions::Controller
  def index
    data = statuses
      .by_state(params[:state])
      .by_archived(params[:archived]&.to_bool)
      .positioned
      .ordered_by_name
    render_success :ok, json: data.map { |s| status_props(s) }
  end

  def show
    render_success :ok, json: status_props(status)
  end

  def create
    status = statuses.build(status_params)
    if status.save
      render_success :ok, json: status_props(status)
    else
      render_error :unprocessable_entity, errors: status
    end
  end

  def update
    if status.update(status_params)
      render_success :ok, json: status_props(status)
    else
      render_error :unprocessable_entity, errors: status
    end
  end

  def destroy
    if status.destroy
      render_success :ok
    else
      render_error :unprocessable_entity, errors: status
    end
  end

  private
    def statuses
      current_school.admission_statuses
    end

    def status
      @status ||= statuses.find_by(id: params[:id])
    end

    def status_params
      params.require(:status).permit(:state, :name, :archived)
    end

    def status_props(status)
      {}.tap do |props|
        props[:id] = status.id
        props[:name] = status.name
        props[:state] = status.state
        props[:archived] = status.archived
        props[:title] = status.decorate.title
        props[:has_applicants] = status.applicants.any? if action_name.to_sym == :show
      end
    end
end
