1# frozen_string_literal: true
2# rubocop: disable Graphql/ResolverType
3
4module Resolvers
5  class GroupPackagesResolver < PackagesBaseResolver
6    # The GraphQL type is defined in the extended class
7
8    argument :sort, Types::Packages::PackageGroupSortEnum,
9      description: 'Sort packages by this criteria.',
10      required: false,
11      default_value: :created_desc
12
13    GROUP_SORT_TO_PARAMS_MAP = SORT_TO_PARAMS_MAP.merge({
14      project_path_desc: { order_by: 'project_path', sort: 'desc' },
15      project_path_asc: { order_by: 'project_path', sort: 'asc' }
16    }).freeze
17
18    def ready?(**args)
19      context[self.class] ||= { executions: 0 }
20      context[self.class][:executions] += 1
21      raise GraphQL::ExecutionError, "Packages can be requested only for one group at a time" if context[self.class][:executions] > 1
22
23      super
24    end
25
26    def resolve(sort:, **filters)
27      return unless packages_available?
28
29      ::Packages::GroupPackagesFinder.new(current_user, object, filters.merge(GROUP_SORT_TO_PARAMS_MAP.fetch(sort))).execute
30    end
31  end
32end
33# rubocop: enable Graphql/ResolverType
34