class TagChildrenController < ApplicationController
  def create
    return head :unauthorized unless current_user
    return head :forbidden unless current_user.admin?

    parent_id = params[:parent_id]
    child_id = params[:child_id]
    return render_bad_request('parent_id は必須です．') if parent_id.blank?
    return render_bad_request('child_id は必須です．') if child_id.blank?

    parent = Tag.find(parent_id)
    child = Tag.find(child_id)
    return render_bad_request('ニコニコ・タグの階層は変更できません．') if parent.nico? || child.nico?

    ApplicationRecord.transaction do
      TagVersioning.ensure_snapshot!(child, created_by_user: current_user)

      TagImplication.find_or_create_by!(parent_tag: parent, tag: child)
      TagVersionRecorder.record!(tag: child, event_type: :update, created_by_user: current_user)
    end

    head :no_content
  end

  def destroy
    return head :unauthorized unless current_user
    return head :forbidden unless current_user.admin?

    parent_id = params[:parent_id]
    child_id = params[:child_id]
    return render_bad_request('parent_id は必須です．') if parent_id.blank?
    return render_bad_request('child_id は必須です．') if child_id.blank?

    parent = Tag.find(parent_id)
    child = Tag.find(child_id)
    return render_bad_request('ニコニコ・タグの階層は変更できません．') if parent.nico? || child.nico?

    ApplicationRecord.transaction do
      TagVersioning.ensure_snapshot!(child, created_by_user: current_user)

      TagImplication.find_by(parent_tag: parent, tag: child)&.destroy!
      TagVersionRecorder.record!(tag: child, event_type: :update, created_by_user: current_user)
    end

    head :no_content
  end
end
