class Admin::Legacy::Nursing::LogsController < Admin::Legacy::Nursing::Controller
  include DateRangeHelper

  def index
    data = logs.by_students(params[:student_ids]).with_date_range(datetime_range(params[:dates]))
    render_success :ok, json: data.map { |l| log_props(l) }
  end

  def show
    render_success :ok, json: log_props(log)
  end

  def create
    log = logs.build(log_params)
    if log.save
      render_success :ok, json: log_props(log)
    else
      render_error :unprocessable_entity, errors: log
    end
  end

  def update
    if log.update(log_params)
      render_success :ok, json: log_props(log)
    else
      render_error :unprocessable_entity, errors: log
    end
  end

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

  def report
    Reporting::Nursing::LogsJob.perform_async(
      current_school.id,
      current_user.id,
      dates: params[:dates],
      student_id: params[:student_ids]
    )
  end

  private
    def logs
      current_school.nursing_logs.includes(:student, :complaint, :author)
    end

    def log
      @log ||= logs.find_by(id: params[:id])
    end

    def log_params
      params.permit(:entry_date, :description, :treatment, :alert).merge(associations)
    end

    def associations
      {}.tap do |props|
        props[:complaint] = current_school.nursing_complaints.find_by(id: params[:complaint_id])
        return props unless action_name.to_sym == :create

        props[:author] = current_user
        props[:student] = current_school.students.find_by(id: params[:student_id])
      end
    end

    def log_props(log)
      {
        id: log.id,
        student_id: log.student_id,
        name: log.decorate.student_name,
        author_id: log.author_id,
        author_name: log.decorate.author_name,
        complaint_id: log.complaint_id? ? log.complaint_id : nil,
        description: log.description,
        complaint_description: log.decorate.complaint_description,
        treatment: log.treatment,
        alert: log.alert?,
        entry_date: log.entry_date,
        date: log.decorate.standardized_date,
        time: log.decorate.time
      }
    end
end
