class Api::V1::ProjectTopicsController < Api::V1::BaseController 

  def index 
    @project_topics = ProjectTopic
    @project_topics = @project_topics.ransack(name_cont: params[:keyword]) if params[:keyword].present?
    # @project_topics = @project_topics.includes(:projects)
    @project_topics = kaminary_select_paginate(@project_topics)
  end

  def create 
    ActiveRecord::Base.transaction do 
      @project = Project.find_by_id(create_params[:project_id])
      return render_not_found unless @project.present?
      return render_error("请输入项目搜索标签名称.") unless create_params[:name].present? 
      
      @project_topic = ProjectTopic.find_or_create_by!(name: create_params[:name].downcase)
      @project_topic_ralate = @project_topic.project_topic_ralates.find_or_create_by!(project_id: create_params[:project_id])

      if @project_topic.present? && @project_topic_ralate.present? 
        render_ok
      else 
        render_error("项目关联搜索标签失败.")
      end
    end
  end

  def destroy 
    ActiveRecord::Base.transaction do 
      @project = Project.find_by_id(create_params[:project_id])
      return render_not_found unless @project.present?

      @project_topic = ProjectTopic.find_by_id(params[:id])
      @project_topic_ralate = @project_topic.project_topic_ralates.find_by(project_id: @project.id)
      if @project_topic_ralate.destroy! 
        render_ok 
      else 
        render_error("项目取消关联搜索标签失败.")
      end
    end
  end

  private 
  def create_params
    params.permit(:project_id, :name)
  end
end