# frozen_string_literal: true

class UxToolkitTeamWorkloadController < ApplicationController
  before_action :require_login
  before_action :find_project
  before_action :require_team_workload_permission

  helper :issues
  helper :projects
  helper :ux_toolkit_team_workload

  def index
    @available_projects = workload_projects
    @selected_project = selected_filter_project
    @include_closed = params[:include_closed].to_s == '1'
    @user_status = params[:user_status].presence_in(%w[active all]) || 'active'
    @active_users_only = @user_status == 'active'

    service = RedmineUxToolkit::Services::TeamWorkload.new(
      user: User.current,
      project: @selected_project,
      project_ids: workload_project_scope_ids,
      include_closed: @include_closed,
      active_users_only: @active_users_only
    )

    @stale_days = service.stale_days
    @high_priority_ids = service.high_priority_ids
    @workload_rows = service.rows
  end

  private

  def find_project
    return if params[:project_id].blank?

    project_key = params[:project_id].to_s
    @project = Project.find_by(identifier: project_key)
    @project ||= Project.find_by(id: project_key) if project_key.match?(/\A\d+\z/)
    render_404 unless @project
  end

  def require_team_workload_permission
    return true if User.current.admin?
    return true if @project && User.current.allowed_to?(:view_ux_toolkit_team_workload, @project)
    return true if workload_projects.any?

    render_403
    false
  end

  def workload_projects
    @workload_projects ||= begin
      scope = User.current.admin? ? Project.active : Project.visible(User.current).active
      scope.to_a.select {|project| User.current.admin? || User.current.allowed_to?(:view_ux_toolkit_team_workload, project)}
    end
  end

  def selected_filter_project
    requested_id = params[:project_filter_id].presence
    return @project if requested_id.nil? && @project
    return nil if requested_id.blank?

    workload_projects.find {|project| project.id.to_s == requested_id.to_s}
  end

  def workload_project_scope_ids
    return nil if User.current.admin? || @selected_project

    workload_projects.map(&:id)
  end
end
