# frozen_string_literal: true

module RedmineUxToolkit
  module Services
    module IssueQuickStatusActions
      module_function

      def enabled?
        settings.fetch('enable_quick_status_actions', '0').to_s == '1'
      end

      def configured_status_ids
        Array(settings['quick_status_action_status_ids'])
          .flat_map { |value| value.to_s.split(',') }
          .map(&:strip)
          .select { |value| value.match?(/\A\d+\z/) }
          .map(&:to_i)
          .uniq
      end

      def configured?(status)
        status && configured_status_ids.include?(status.id)
      end

      def status_by_id(status_id)
        status_id = status_id.to_s
        return nil unless status_id.match?(/\A\d+\z/)

        IssueStatus.find_by(id: status_id.to_i)
      end

      def available_statuses(issue, user = User.current)
        return [] unless enabled?
        return [] unless issue && user&.logged?
        return [] unless issue.visible?(user)
        return [] unless RedmineUxToolkit::Compatibility.issue_editable?(issue, user)
        return [] unless RedmineUxToolkit::Compatibility.safe_attribute?(issue, 'status_id', user)

        ids = configured_status_ids
        return [] if ids.empty?

        # Redmine applies tracker, project, role, author and assignee workflow rules here.
        allowed_statuses = RedmineUxToolkit::Compatibility.allowed_issue_statuses(issue, user)
        allowed_statuses.select do |status|
          ids.include?(status.id) && status.id != issue.status_id
        end
      end

      def status_allowed?(issue, user = User.current, status = nil)
        status && available_statuses(issue, user).map(&:id).include?(status.id)
      end

      def settings
        Setting.plugin_redmine_ux_toolkit || {}
      end
    end
  end
end
