# frozen_string_literal: true

module UxToolkitProjectHealthHelper
  def ux_toolkit_project_health_count_link(count, project, metric)
    return content_tag(:span, count, class: 'ux-toolkit-workload-count') if count.to_i <= 0

    if metric == :open_checklist_items
      return content_tag(:span,
                         count,
                         class: "ux-toolkit-workload-count ux-toolkit-workload-count-#{metric}")
    end

    link_to count,
            ux_toolkit_project_health_issues_path(project, metric),
            class: "ux-toolkit-workload-count ux-toolkit-workload-count-#{metric}"
  end

  def ux_toolkit_project_health_issues_path(project, metric)
    filters = {
      'set_filter' => '1',
      'f' => ['status_id'],
      'op' => {'status_id' => 'o'}
    }

    add_project_health_metric_filter(filters, metric)
    project_issues_path(project, filters)
  end

  private

  def add_project_health_metric_filter(filters, metric)
    case metric
    when :overdue
      yesterday = (RedmineUxToolkit::Compatibility.user_today - 1).to_s
      add_project_health_date_filter(filters, 'due_date', '<=', yesterday)
    when :due_today
      add_project_health_date_filter(filters, 'due_date', '=', RedmineUxToolkit::Compatibility.user_today.to_s)
    when :unassigned
      filters['f'] << 'assigned_to_id'
      filters['op']['assigned_to_id'] = '!*'
    when :stale
      stale_date = (RedmineUxToolkit::Compatibility.user_today - @stale_days.to_i).to_s
      add_project_health_date_filter(filters, 'updated_on', '<=', stale_date)
    when :open_subtasks
      filters['f'] << 'parent_id'
      filters['op']['parent_id'] = '*'
    end
  end

  def add_project_health_date_filter(filters, field, operator, value)
    filters['f'] << field
    filters['op'][field] = operator
    filters['v'] ||= {}
    filters['v'][field] = [value]
  end
end
