# frozen_string_literal: true

class UxToolkitProjectHealthController < ApplicationController
  before_action :require_login
  before_action :require_project_health_permission

  helper :issues
  helper :projects
  helper :ux_toolkit_project_health

  def index
    @active_projects_only = params.key?(:active_projects_only) ? params[:active_projects_only].to_s == '1' : true
    @include_archived = params[:include_archived].to_s == '1'
    @available_projects = project_health_projects

    service = RedmineUxToolkit::Services::ProjectHealth.new(
      user: User.current,
      project_ids: project_health_project_scope_ids,
      active_projects_only: @active_projects_only,
      include_archived: @include_archived
    )

    @stale_days = service.stale_days
    @project_health_rows = service.rows
  end

  private

  def require_project_health_permission
    return true if User.current.admin?
    return true if project_health_projects.any?

    render_403
    false
  end

  def project_health_projects
    @project_health_projects ||= begin
      scope = User.current.admin? ? Project.all : Project.visible(User.current)
      scope.to_a.select do |project|
        User.current.admin? || User.current.allowed_to?(:view_ux_toolkit_project_health, project)
      end
    end
  end

  def project_health_project_scope_ids
    return nil if User.current.admin?

    project_health_projects.map(&:id)
  end
end
