class Employee::AddressBook::Contacts::CallNotesController < Employee::Controller
  def index
    render_success :ok, json: call_notes.includes(:author).decorate.map { |note| props(note) }
  end

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

  def create
    note = contact.call_notes.build(note_params)
    note.author = current_employee
    if note.save
      render_success :created, json: props(note.decorate)
    else
      render_error :unprocessable_entity, errors: note.errors
    end
  end

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

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

  private
    def contact
      @contact ||= current_school.contacts.find_by(id: params[:contact_id])
    end

    def call_notes
      contact.call_notes.where(private: false)
        .or(
          current_employee.contact_call_notes
            .where(contact_id: params[:contact_id], private: true)
        )
    end

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

    def note_params
      params.permit(:date, :subject, :message, :reminder, :private, :status)
    end

    def props(note)
      {
        id: note.id,
        contact_id: note.contact_id,
        author_id: note.author_id,
        author_name: note.author_full_name(:reverse),
        date: note.date,
        subject: note.subject,
        message: note.message,
        reminder: note.reminder,
        private: note.private,
        status: note.status
      }
    end
end
