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

module FormUpdater::Concerns::AppliesTaskbarState
  extend ActiveSupport::Concern

  SKIP_FIELDS = %w[attachments].freeze

  class_methods do
    def apply_state_group_keys(group_keys)
      @apply_state_group_keys ||= group_keys
    end
  end

  def resolve
    if current_taskbar.present? && should_apply?
      apply_taskbar_state
    end

    super
  end

  private

  def apply_taskbar_state
    apply_value = FormUpdater::ApplyValue.new(context:, data:, result:)

    apply_state_group_keys = self.class.instance_variable_get(:@apply_state_group_keys)

    current_taskbar.state.each_pair do |field, value|
      next if SKIP_FIELDS.include?(field)

      if apply_state_group_keys.present? && apply_state_group_keys.include?(field) && value.is_a?(Hash)
        value.each_pair do |sub_field, sub_value|
          next if SKIP_FIELDS.include?(sub_field)

          apply_value.perform(field: sub_field, config: { 'value' => sub_value }, include_blank: true, parent_field: field)
        end
      else
        apply_value.perform(field: field, config: { 'value' => value }, include_blank: true)
      end
    end

    # When no object exists, we can ignore the additional check.
    return if object.blank?

    apply_taskbar_object_defaults(apply_value)
  end

  def apply_taskbar_object_defaults(apply_value)
    apply_state_group_keys = self.class.instance_variable_get(:@apply_state_group_keys)

    # We need to check the current dirty fields, to restore maybe some default value from the current ticket.
    meta[:dirty_fields]&.each do |field|
      next if SKIP_FIELDS.include?(field)

      # Check first on the first level if it's present in the current state.
      next if current_taskbar.state.key?(field)

      next if apply_state_group_keys.present? && apply_state_group_keys.any? { |group_key| current_taskbar.state[group_key]&.key?(field) }

      next if !object_field?(field)

      # Through the same comparison the store path uses, so that the two cannot answer differently
      #   for a value whose submitted form is not the record's own (see #object_field_changed?).
      next if !object_field_changed?(field, data[field])

      apply_value.perform(field: field, config: { 'value' => object_field_value(field) }, include_blank: true)
    end
  end

  # Memoized including nil: one round trip resolves one taskbar, and the apply/store paths read
  #   it repeatedly - each call is another GlobalID lookup with authorization.
  def current_taskbar
    return @current_taskbar if defined?(@current_taskbar)

    id = meta.dig(:additional_data, 'taskbarId')

    @current_taskbar = id.present? ? Gql::ZammadSchema.authorized_object_from_id(id, type: Taskbar, user: context[:current_user]) : nil
  end

  def should_apply?
    meta.dig(:additional_data, 'applyTaskbarState') == true || meta[:initial]
  end
end
