001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.revetsec.scim;
018
019import static java.util.Objects.requireNonNull;
020
021import com.google.errorprone.annotations.CheckReturnValue;
022
023import org.jspecify.annotations.NonNull;
024import org.jspecify.annotations.Nullable;
025
026import java.util.*;
027
028import javax.annotation.concurrent.Immutable;
029import javax.annotation.concurrent.NotThreadSafe;
030
031/** Application-authored page framing for one approved query; storage and count accuracy are app-owned.
032 * INDEX pages require a nonnegative accurate totalResults and a consistent result window. CURSOR
033 * pages declare more results exactly when a nextCursor is present; the first page has no
034 * previousCursor. A short page alone does not prove exhaustion. For either method, a zero count
035 * requires accurate totalResults, empty resources and no traversal cursors or more-results flag.
036 * Construction checks framing and resource-type identity, not the truth of storage metadata or
037 * cursor authenticity. The originating provider checks private query/resource associations before
038 * rendering the page.
039 * @since 1.0.0
040 */
041@Immutable
042@CheckReturnValue
043public final class ScimListPage {
044    private final @NonNull ScimQuery query;
045    private final @NonNull List<@NonNull ScimResource> resources;
046    private final @Nullable Long totalResults;
047    private final @Nullable String nextCursor;
048    private final @Nullable String previousCursor;
049    private final boolean moreResultsAvailable;
050
051    @SuppressWarnings(
052            "ReferenceEquality") // Pages require the originating registration object, not
053                                 // equivalent definitions.
054    private ScimListPage(@NonNull Builder b) {
055        query = b.query;
056        resources = b.resources;
057        totalResults = b.totalResults;
058        nextCursor = b.nextCursor;
059        previousCursor = b.previousCursor;
060        moreResultsAvailable = b.moreResultsAvailable != null && b.moreResultsAvailable;
061        if (resources.size() > query.getCount() || (totalResults != null && totalResults < 0))
062            throw new IllegalArgumentException("Inconsistent SCIM page counts.");
063        if (query.getPaginationMethod() == ScimPaginationMethod.INDEX) {
064            if (totalResults == null
065                    || nextCursor != null
066                    || previousCursor != null
067                    || moreResultsAvailable)
068                throw new IllegalArgumentException("Invalid index page framing.");
069            long start = query.getStartIndex().orElseThrow();
070            if (!resources.isEmpty()
071                    && (start > totalResults || resources.size() > totalResults - start + 1))
072                throw new IllegalArgumentException("Page exceeds total results.");
073        } else {
074            if (moreResultsAvailable != (nextCursor != null)
075                    || (query.isFirstCursorPage() && previousCursor != null))
076                throw new IllegalArgumentException("Invalid cursor page framing.");
077        }
078        if (query.getCount() == 0
079                && (totalResults == null
080                        || nextCursor != null
081                        || previousCursor != null
082                        || moreResultsAvailable
083                        || !resources.isEmpty()))
084            throw new IllegalArgumentException("Invalid count-only page framing.");
085        for (ScimResource r : resources)
086            if (r.getResourceType() != query.getResourceType())
087                throw new IllegalArgumentException("Foreign SCIM page resource type.");
088        if ((nextCursor != null && !cursor(nextCursor, query.maximumCursorCharacters()))
089                || (previousCursor != null
090                        && !cursor(previousCursor, query.maximumCursorCharacters())))
091            throw new IllegalArgumentException("Invalid SCIM cursor.");
092    }
093
094    /** Returns the originating approved query whose bounds and projection frame this page.
095     * @return the original query
096     * @since 1.0.0
097     */
098    public @NonNull ScimQuery getQuery() {
099        return query;
100    }
101
102    /** Returns the immutable application-supplied resource snapshot in represented page order.
103     * Every resource uses the query's exact resource-type registration and the list is no larger
104     * than the query's effective count.
105     * @return the resources
106     * @since 1.0.0
107     */
108    public @NonNull List<@NonNull ScimResource> getResources() {
109        return resources;
110    }
111
112    /** Returns the application's declared accurate nonnegative matching-resource total, when present.
113     * It is required for INDEX and every count-only page; ordinary CURSOR pages may omit it.
114     * @return the declared total, or empty when omitted
115     * @since 1.0.0
116     */
117    public @NonNull Optional<@NonNull Long> getTotalResults() {
118        return Optional.ofNullable(totalResults);
119    }
120
121    /** Returns the application's next-page token, present exactly when more results are declared.
122     * The token's authenticity, context and validity remain application responsibilities.
123     * @return the next cursor, or empty when no next page is declared
124     * @since 1.0.0
125     */
126    public @NonNull Optional<@NonNull String> getNextCursor() {
127        return Optional.ofNullable(nextCursor);
128    }
129
130    /** Returns the application's previous-page token, when available.
131     * The first cursor page, INDEX pages and count-only pages cannot have a previous token.
132     * @return the previous cursor, or empty when unavailable
133     * @since 1.0.0
134     */
135    public @NonNull Optional<@NonNull String> getPreviousCursor() {
136        return Optional.ofNullable(previousCursor);
137    }
138
139    /** Reports the application's more-results declaration, true exactly when nextCursor is present.
140     * A short page does not itself imply false; INDEX and count-only pages require false.
141     * @return whether a next cursor page is declared
142     * @since 1.0.0
143     */
144    public @NonNull Boolean isMoreResultsAvailable() {
145        return moreResultsAvailable;
146    }
147
148    static boolean cursor(@NonNull String value, int maximum) {
149        if (value.isEmpty() || value.length() > maximum) return false;
150        for (int i = 0; i < value.length(); i++) {
151            char c = value.charAt(i);
152            if (!((c >= 'A' && c <= 'Z')
153                    || (c >= 'a' && c <= 'z')
154                    || (c >= '0' && c <= '9')
155                    || c == '-'
156                    || c == '_'
157                    || c == '.'
158                    || c == '~')) return false;
159        }
160        return true;
161    }
162
163    /** Starts page framing for an approved query with empty resources, absent total/cursors and
164     * moreResultsAvailable false. Supply the metadata required by the query's framing before build.
165     * @param query the originating approved query
166     * @return builder
167     * @since 1.0.0
168     */
169    public static @NonNull Builder withQuery(@NonNull ScimQuery query) {
170        return new Builder(requireNonNull(query));
171    }
172
173    /** Returns a redacted diagnostic.
174     * @return description
175     * @since 1.0.0
176     */
177    @Override
178    public @NonNull String toString() {
179        return "ScimListPage{<redacted>}";
180    }
181
182    /** Mutable complete page configuration. Defaults are empty resources, absent total/cursors and
183     * moreResultsAvailable false. Setters replace complete values; build checks the combined framing.
184     * @since 1.0.0
185     */
186    @NotThreadSafe
187    @CheckReturnValue
188    public static final class Builder {
189        private final @NonNull ScimQuery query;
190        private @NonNull List<@NonNull ScimResource> resources = List.of();
191        private @Nullable Long totalResults;
192        private @Nullable String nextCursor;
193        private @Nullable String previousCursor;
194        private @Nullable Boolean moreResultsAvailable;
195
196        private Builder(@NonNull ScimQuery query) {
197            this.query = query;
198        }
199
200        /** Replaces the complete resource snapshot.
201         * @param value resources or null for empty
202         * @return this builder
203         * @since 1.0.0
204         */
205        public @NonNull Builder resources(@Nullable List<@NonNull ScimResource> value) {
206            if (value != null && value.size() > query.getCount())
207                throw new IllegalArgumentException("Too many page resources.");
208            resources = value == null ? List.of() : List.copyOf(value);
209            return this;
210        }
211
212        /** Replaces the application's accurate nonnegative matching-resource total; null restores absence.
213         * INDEX and count-only framing require a total even when no resources are returned.
214         * @param value the declared total, or null to omit it
215         * @return this builder
216         * @since 1.0.0
217         */
218        public @NonNull Builder totalResults(@Nullable Long value) {
219            totalResults = value;
220            return this;
221        }
222
223        /** Replaces the next-page token; null restores absence.
224         * A token must be nonempty unreserved ASCII within the query's cursor bound. The application
225         * owns its authenticity, context and validity. Presence must agree with moreResultsAvailable.
226         * @param value the complete next token, or null for absence
227         * @return this builder
228         * @since 1.0.0
229         */
230        public @NonNull Builder nextCursor(@Nullable String value) {
231            nextCursor = value;
232            return this;
233        }
234
235        /** Replaces the previous-page token; null restores absence.
236         * A token must be nonempty unreserved ASCII within the query's cursor bound. The application
237         * owns its authenticity, context and validity; first, INDEX and count-only pages forbid it.
238         * @param value the complete previous token, or null for absence
239         * @return this builder
240         * @since 1.0.0
241         */
242        public @NonNull Builder previousCursor(@Nullable String value) {
243            previousCursor = value;
244            return this;
245        }
246
247        /** Replaces the more-results declaration; null restores false.
248         * CURSOR framing requires true exactly when nextCursor is present. INDEX and count-only
249         * pages require false.
250         * @param value the complete declaration, or null for false
251         * @return this builder
252         * @since 1.0.0
253         */
254        public @NonNull Builder moreResultsAvailable(@Nullable Boolean value) {
255            moreResultsAvailable = value;
256            return this;
257        }
258
259        /** Checks combined counts, cursors, resource-type identity and page framing, then creates the page.
260         * This does not verify storage/count accuracy or token authenticity. INDEX requires totalResults
261         * and a consistent window; CURSOR requires nextCursor iff moreResultsAvailable and no previous
262         * cursor on the first page. Count-only pages require an accurate total, empty resources and no
263         * traversal cursors or more-results declaration.
264         * @return the immutable page
265         * @throws IllegalArgumentException if trusted page values violate the query's bounds or framing
266         * @since 1.0.0
267         */
268        public @NonNull ScimListPage build() {
269            return new ScimListPage(this);
270        }
271    }
272}