class Admin::Legacy::Service::Students::HistoryController < Admin::Legacy::Service::Controller
  def index
    render_success :ok, json: histories.map { |h| history_props(h) }
  end

  def show
    render_success :ok, json: history_props(history)
  end

  def create
    history = histories.build(history_params)
    if history.save
      render_success :ok
    else
      render_error :unprocessable_entity, errors: history
    end
  end

  def update
    if history.update(history_params)
      render_success :ok
    else
      render_error :unprocessable_entity, errors: history
    end
  end

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

  private
    def histories
      student.service_histories
    end

    def history
      @history ||= histories.find_by(id: params[:id])
    end

    def student
      @student ||= current_school.students.find_by(id: params[:student_id])
    end

    def school_year
      @school_year ||= current_school.school_years.find_by(id: params[:school_year_id])
    end

    def history_params
      params.permit(:approved_hours).merge(set_associations)
    end

    def set_associations
      {}.tap do |prop|
        prop[:school] = current_school
        prop[:school_year] = school_year if school_year
      end
    end

    def history_props(history)
      {
        id: history.id,
        approved_hours: history.approved_hours,
        school_year_id: history.school_year.id,
        school_year_name: history.decorate.school_year_name
      }
    end
end
