# Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

module TestFlags
  def wait_for_test_flag(flag, skip_clearing: false, timeout: Capybara.default_max_wait_time)
    begin
      wait(timeout).until { page.evaluate_script("window.testFlags && window.testFlags.get('#{flag.gsub("'", "\\'")}', #{skip_clearing})") }
    rescue BrowserTestHelper::Waiter::TimeoutError
      raise "Test flag #{flag} not set"
    end
  end

  def wait_for_gql(filename, number: 1, skip_clearing: false)
    gql = Rails.root.join("app/frontend/#{filename}").read
    operation = %r{^\w+ \w+}.match(gql).to_s
    wait_for_test_flag("__gql #{operation} #{number}", skip_clearing: skip_clearing)
  end

  def wait_for_query(name, number: 1, skip_clearing: false)
    wait_for_test_flag("__gql query #{name} #{number}", skip_clearing: skip_clearing)
  end

  def wait_for_mutation(name, number: 1, skip_clearing: false)
    wait_for_test_flag("__gql mutation #{name} #{number}", skip_clearing: skip_clearing)
  end

  def wait_for_subscription_update(name, number: 1, skip_clearing: false)
    wait_for_test_flag("__gql subscription #{name} #{number}", skip_clearing: skip_clearing)
  end

  def wait_for_subscription_start(name, entity: nil, scope: nil, skip_clearing: true)
    wait_for_test_flag("__gql subscription #{name} start", skip_clearing: skip_clearing)

    # The start flag only means the client received the initial subscription response.
    # The server subscribes to the Redis event stream asynchronously (stream_from),
    # so an event triggered right away can still get lost. Wait until Redis reports
    # an active subscriber for the event stream before continuing.
    begin
      wait.until { GraphqlEventStream.subscribed?(name, entity: entity, scope: scope) }
    rescue BrowserTestHelper::Waiter::TimeoutError
      raise "GraphQL event stream for subscription #{name} has no subscriber"
    end
  end

  def wait_for_form_to_settle(form)
    wait_for_test_flag("#{form}.settled")
  end

  def wait_for_form_updater(form_updater_call_number = 1)
    wait_for_gql('shared/components/Form/graphql/queries/formUpdater.graphql', number: form_updater_call_number)
  end

  def wait_for_form_autofocus(form)
    wait_for_test_flag("#{form}.focused")
  end

  def wait_for_editor_ready(editor)
    wait_for_test_flag(editor_test_flag(editor, 'ready'))
  end

  def editor_test_flag(editor, state)
    input = editor.respond_to?(:input_element) ? editor.input_element : editor

    "#{input['data-form-id']}.#{input['name']}.editor.#{state}"
  end
end

RSpec.configure do |config|
  config.include TestFlags, type: :system
end
