class Employee::AddressBook::Companies::NotesController < Employee::Controller
  def index
    render_success :ok, json: notes.includes(:author).map { |c| props(c) }
  end

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

  def create
    note = notes.build(note_params)
    note.author = current_user
    if note.save
      render_success :created, json: props(note)
    else
      render_error :unprocessable_entity, errors: note
    end
  end

  def update
    if note.update(note_params)
      render_success :ok, json: 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 company
      @company ||= current_school.companies.find_by(id: params[:company_id])
    end

    def notes
      company.notes
    end

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

    def note_params
      params.permit(:datetime, :subject, :message)
    end

    def props(note)
      {
        id: note.id,
        datetime: note.datetime,
        subject: note.subject,
        message: note.message,
        full_name: note.decorate.full_name(:reverse)
      }
    end
end
