# frozen_string_literal: true

class UxToolkitFavoriteProjectsController < ApplicationController
  before_action :require_login

  def index
    @favorite_projects = UxToolkitFavoriteProject.visible_for(User.current).map(&:project).compact
  end

  def create
    project = find_visible_project
    return project_not_visible unless project

    favorite = UxToolkitFavoriteProject.find_or_initialize_by(
      user_id: User.current.id,
      project_id: project.id
    )

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

    redirect_back_or_project(project)
  end

  def destroy
    project = find_project
    favorite = find_current_user_favorite(project)
    favorite&.destroy

    flash[:notice] = l(:notice_ux_toolkit_project_removed_from_favorites)
    redirect_back_or_project(project)
  end

  private

  def find_visible_project
    find_project(Project.visible(User.current))
  end

  def find_project(scope = Project)
    project_id = params[:project_id].to_s
    project = scope.find_by(identifier: project_id)
    project || (project_id.match?(/\A\d+\z/) ? scope.find_by(id: project_id.to_i) : nil)
  end

  def find_current_user_favorite(project)
    project_id = project&.id || numeric_project_id_param
    return unless project_id

    UxToolkitFavoriteProject.find_by(user_id: User.current.id, project_id: project_id)
  end

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

  def redirect_back_or_project(project)
    fallback = if project && project.visible?(User.current)
                 project_path(project)
               else
                 ux_toolkit_my_favorite_projects_path
               end

    redirect_back_or_default(fallback, referer: true)
  end

  def project_not_visible
    flash[:error] = l(:error_ux_toolkit_project_not_visible)
    redirect_back_or_default(ux_toolkit_my_favorite_projects_path, referer: true)
  end
end
