class TagsController < ApplicationController
  def index
    post_id = params[:post]
    tags = if post_id.present?
             Tag.joins(:posts).where(posts: { id: post_id })
           else
             Tag.all
           end
    render json: tags
  end

  def autocomplete
    q = params[:q].to_s.strip
    return render json: [] if q.blank?

    tags = (Tag
            .where('(category = ? AND name LIKE ?) OR name LIKE ?',
                   'nico', "nico:#{ q }%", "#{ q }%")
            .order('post_count DESC, name ASC')
            .limit(20))
    render json: tags
  end

  def show
    tag = Tag.find(params[:id])
    render json: tag
  end

  def show_by_name
    tag = Tag.find_by(name: params[:name])
    if tag
      render json: tag
    else
      head :not_found
    end
  end

  def create
  end

  def update
  end

  def destroy
  end
end
