class Admin::Legacy::Nursing::Students::MedicationsController < Admin::Legacy::Nursing::Controller
  def index
    render_success :ok, json: medications.map { |m| medication_props(m) }
  end

  def show
    render_success :ok, json: medication_props(medication)
  end

  def create
    medication = medications.build(medication: nursing_medication)
    if medication.save
      render_success :ok, message: 'Over The Counter added.', json: medication_props(medication)
    else
      render_error :unprocessable_entity, message: 'Something went wrong'
    end
  end

  def update
    if medication.update(medication_params)
      render_success :ok, json: medication_props(medication)
    else
      render_error :unprocessable_entity, errors: medication
    end
  end

  def destroy
    if medication.destroy
      render_success :ok, object: 'Over The Counter'
    else
      render_error :unprocessable_entity, errors: prescription
    end
  end

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

    def medications
      student.nursing_medications.includes(:medication)
    end

    def medication
      @medication ||= medications.find_by(id: params[:id])
    end

    def nursing_medications
      current_school.nursing_medications
    end

    def nursing_medication
      @nursing_medication ||= nursing_medications.find_by(id: params[:medication_id])
    end

    def medication_params
      params.permit(:notes)
    end

    def medication_props(medication)
      {
        id: medication.id,
        medication_id: medication.medication_id? ? medication.medication_id : nil,
        notes: medication.notes,
        name: medication.decorate.name,
        description: medication.decorate.description
      }
    end
end
