# frozen_string_literal: true

# Tags Controller
class TagsController < ApplicationController
  load_and_authorize_resource :project
  load_and_authorize_resource :tag_category, through: :project
  load_and_authorize_resource through: :tag_category

  before_action :set_tag, only: %i[show edit update destroy]
  before_action :set_tag_category

  def create_tag
    tag = Tag.new(name: params["tagName"], tag_category_id: params["categoryId"])
    if tag.save!
      render json: { status: "ok", new_tag: tag }
    else
      render json: { status: "error" }
    end
  end

  def delete_tag
    Tag.destroy(params["id"])
    render json: { status: "ok" }
  end

  def edit_tag
    tag = Tag.find(params["tagId"])
    if tag.nil?
      render json: { status: "error" }
    else
      tag.update!(name: params["tagName"])
      render json: { status: "ok" }
    end
  end

  # GET /tags or /tags.json
  def index
    @tags = @tag_category.tags
  end

  # GET /tags/1 or /tags/1.json
  def show; end

  # GET /tags/new
  def new
    @tag = @tag_category.tags.new
  end

  # GET /tags/1/edit
  def edit; end

  # POST /tags or /tags.json
  def create
    @tag = @tag_category.tags.new(tag_params)

    respond_to do |format|
      if @tag.save
        format.html { redirect_to @tag_category, notice: "Tag was successfully created." }
        format.json { render :show, status: :created, location: @tag }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @tag.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /tags/1 or /tags/1.json
  def update
    respond_to do |format|
      if @tag.update(tag_params)
        format.html { redirect_to @tag_category, notice: "Tag was successfully updated." }
        format.json { render :show, status: :ok, location: @tag }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @tag.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /tags/1 or /tags/1.json
  def destroy
    @tag.destroy

    respond_to do |format|
      format.html { redirect_to @tag_category, notice: "Tag was successfully destroyed." }
      format.json { head :no_content }
    end
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def set_tag
    @tag = Tag.find(params[:id])
  end

  def set_tag_category
    @tag_category = TagCategory.find(params[:tag_category_id])
  end

  # Only allow a list of trusted parameters through.
  def tag_params
    params.require(:tag).permit(:name)
  end
end
