class Admin::Legacy::HumanResources::Employees::NotesController <
    Admin::Legacy::HumanResources::Controller
  def index
    render_success :ok, json: notes.includes(:author, :employee).ordered.map { |n| note_props(n) }
  end

  def show
    render_success :ok, json: note_props(note)
  end

  def create
    note = notes.build(note_params)
    if note.save
      render_success :ok, json: note_props(note)
    else
      render_error :unprocessable_entity, errors: note
    end
  end

  def update
    if note.update(note_params)
      render_success :ok, json: note_props(note)
    else
      render_error :unprocessable_entity, errors: note
    end
  end

  def destroy
    if note.destroy
      render_success :ok
    else
      render_error :unprocessable_entity
    end
  end

  private
    def employee
      @employee ||= current_school.employees.find_by(id: params[:employee_id])
    end

    def notes
      employee.notes
    end

    def note
      @note ||= notes.find_by(id: params[:id])
    end

    def set_defaults
      { author_id: current_user.id }
    end

    def note_params
      params.permit(:subject, :body).merge(set_defaults)
    end

    def note_props(note)
      {
        id: note.id,
        subject: note.subject,
        body: note.body,
        employee_name: note.employee.full_name(:reverse),
        date: note.date.to_date.strftime('%m/%d/%Y'),
        author: note.author&.full_name(:reverse)
      }
    end
end
