class Admin::Legacy::Nursing::Students::PrescriptionsController < Admin::Legacy::Nursing::Controller
  def index
    render_success :ok, json: prescriptions.map { |p| prescription_props(p) }
  end

  def show
    render_success :ok, json: prescription_props(prescription)
  end

  def create
    prescription = prescriptions.build(prescription_params)

    if prescription.save
      render_success :ok, json: prescription_props(prescription)
    else
      render_error :unprocessable_entity, errors: prescription
    end
  end

  def update
    if prescription.update(prescription_params)
      render_success :ok, json: prescription_props(prescription)
    else
      render_error :unprocessable_entity, errors: prescription
    end
  end

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

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

    def prescriptions
      student.nursing_prescriptions
    end

    def prescription
      @prescription ||= prescriptions.find_by(id: params[:id])
    end

    def prescription_params
      params.permit(
        :medication,
        :notes,
        :dose,
        :route,
        :self_administer,
        :start_date,
        :stop_date,
        :schedule
      )
    end

    def prescription_props(prescription)
      {}.tap do |props|
        props[:id] = prescription.id
        props[:medication] = prescription.medication
        props[:notes] = prescription.notes
        props[:dose] = prescription.dose
        props[:route] = prescription.route
        props[:self_administer] = prescription.self_administer
        props[:start_date] = prescription.start_date
        props[:stop_date] = prescription.stop_date
        props[:schedule] = prescription.schedule
        return props unless action_name.to_sym == :show

        props[:has_distribution] = prescription.distributions.exists?
      end
    end
end
