# frozen_string_literal: true

module RedmineUxToolkit
  module Services
    module IssueAssignToMe
      module_function

      def enabled?
        settings = Setting.plugin_redmine_ux_toolkit || {}
        settings.fetch('enable_assign_to_me_button', '1').to_s != '0'
      end

      def available?(issue, user = User.current)
        return false unless enabled?
        return false if issue.assigned_to_id == user.id

        assignable_to_user?(issue, user)
      end

      def assignable_to_user?(issue, user = User.current)
        return false unless issue && user&.logged?
        return false unless issue.visible?(user)
        return false unless RedmineUxToolkit::Compatibility.issue_editable?(issue, user)

        # Redmine applies tracker/project role assignability through Issue#assignable_users.
        RedmineUxToolkit::Compatibility.safe_attribute?(issue, 'assigned_to_id', user) &&
          RedmineUxToolkit::Compatibility.issue_assignable_to?(issue, user)
      end
    end
  end
end
