# frozen_string_literal: true

class UxToolkitFavoriteQueriesController < ApplicationController
  before_action :require_login

  def index
    @favorite_queries = UxToolkitFavoriteQuery.visible_for(User.current).map(&:query).compact
  end

  def create
    query = find_visible_query
    return query_not_visible unless query

    favorite = UxToolkitFavoriteQuery.find_or_initialize_by(
      user_id: User.current.id,
      query_id: query.id
    )

    if favorite.persisted?
      flash[:notice] = l(:notice_ux_toolkit_query_already_favorite)
    elsif favorite.save
      flash[:notice] = l(:notice_ux_toolkit_query_added_to_favorites)
    else
      flash[:error] = favorite.errors.full_messages.to_sentence
    end

    redirect_back_or_query(query)
  end

  def destroy
    query = find_query
    favorite = find_current_user_favorite(query)
    favorite&.destroy

    flash[:notice] = l(:notice_ux_toolkit_query_removed_from_favorites)
    redirect_back_or_query(query)
  end

  private

  def find_visible_query
    query_id = numeric_query_id_param
    return unless query_id

    IssueQuery.visible(User.current).find_by(id: query_id)
  end

  def find_query
    query_id = numeric_query_id_param
    return unless query_id

    IssueQuery.find_by(id: query_id)
  end

  def find_current_user_favorite(query)
    query_id = query&.id || numeric_query_id_param
    return unless query_id

    UxToolkitFavoriteQuery.find_by(user_id: User.current.id, query_id: query_id)
  end

  def numeric_query_id_param
    query_id = params[:query_id].to_s
    query_id.to_i if query_id.match?(/\A\d+\z/)
  end

  def redirect_back_or_query(query)
    fallback = if query&.visible?(User.current)
                 issue_query_path(query)
               else
                 ux_toolkit_my_favorite_queries_path
               end

    redirect_back_or_default(fallback, referer: true)
  end

  def issue_query_path(query)
    if query.project
      project_issues_path(query.project, query_id: query.id)
    else
      issues_path(query_id: query.id)
    end
  end

  def query_not_visible
    flash[:error] = l(:error_ux_toolkit_query_not_visible)
    redirect_back_or_default(ux_toolkit_my_favorite_queries_path, referer: true)
  end
end
