# frozen_string_literal: true

module UxToolkitTeamWorkloadHelper
  def ux_toolkit_team_workload_path_for(project)
    project ? project_ux_toolkit_team_workload_path(project) : ux_toolkit_team_workload_path
  end

  def ux_toolkit_workload_count_link(count, user, metric)
    return content_tag(:span, count, class: 'ux-toolkit-workload-count') if count.to_i <= 0

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

  def ux_toolkit_workload_issues_path(user, metric)
    filters = {
      'set_filter' => '1',
      'f' => ['assigned_to_id'],
      'op' => {'assigned_to_id' => '='},
      'v' => {'assigned_to_id' => [user.id.to_s]}
    }

    add_status_filter(filters) unless @include_closed
    add_project_filter(filters) if @selected_project && !@project
    add_project_scope_filter(filters) if @selected_project.nil? && !User.current.admin?
    add_metric_filter(filters, metric)

    @selected_project ? project_issues_path(@selected_project, filters) : issues_path(filters)
  end

  private

  def add_status_filter(filters)
    filters['f'] << 'status_id'
    filters['op']['status_id'] = 'o'
  end

  def add_project_filter(filters)
    filters['f'] << 'project_id'
    filters['op']['project_id'] = '='
    filters['v']['project_id'] = [@selected_project.id.to_s]
  end

  def add_project_scope_filter(filters)
    project_ids = Array(@available_projects).map(&:id)
    return if project_ids.empty?

    filters['f'] << 'project_id'
    filters['op']['project_id'] = '='
    filters['v']['project_id'] = project_ids.map(&:to_s)
  end

  def add_metric_filter(filters, metric)
    case metric
    when :overdue
      add_date_filter(filters, 'due_date', '<=', RedmineUxToolkit::Compatibility.user_today.to_s)
    when :due_today
      add_date_filter(filters, 'due_date', '=', RedmineUxToolkit::Compatibility.user_today.to_s)
    when :stale
      stale_date = (RedmineUxToolkit::Compatibility.user_today - @stale_days.to_i).to_s
      add_date_filter(filters, 'updated_on', '<=', stale_date)
    when :high_priority
      return if @high_priority_ids.blank?

      filters['f'] << 'priority_id'
      filters['op']['priority_id'] = '='
      filters['v']['priority_id'] = @high_priority_ids.map(&:to_s)
    when :open
      add_status_filter(filters) unless filters['op'].key?('status_id')
    end
  end

  def add_date_filter(filters, field, operator, value)
    filters['f'] << field
    filters['op'][field] = operator
    filters['v'][field] = [value]
  end
end
