import { getRouterContext } from "../router-context.js";
/**
 * Creates segment resolution middleware
 *
 * Only runs on cache miss (state.cacheHit === false).
 * Uses resolveAllSegmentsWithRevalidation from RouterContext to resolve segments.
 */
export function withSegmentResolution(ctx, state) {
    return async function* (source) {
        const pipelineStart = performance.now();
        const ms = ctx.metricsStore;
        // IMPORTANT: Always iterate source first to give cache-lookup a chance
        // to run and set state.cacheHit. Without this, cache-lookup never executes!
        for await (const segment of source) {
            yield segment;
        }
        // If cache hit, segments were already yielded by cache lookup
        if (state.cacheHit) {
            if (ms) {
                ms.metrics.push({ label: "pipeline:segment-resolve", duration: performance.now() - pipelineStart, startTime: pipelineStart - ms.requestStart });
            }
            return;
        }
        const { resolveAllSegmentsWithRevalidation, resolveAllSegments } = getRouterContext();
        const Store = ctx.Store;
        if (ctx.isFullMatch) {
            // Full match (document request) - simple resolution without revalidation
            const segments = await Store.run(() => resolveAllSegments(ctx.entries, ctx.routeKey, ctx.matched.params, ctx.handlerContext, ctx.loaderPromises));
            // Update state with resolved segments
            state.segments = segments;
            state.matchedIds = segments.map((s) => s.id);
            // Yield all resolved segments
            for (const segment of segments) {
                yield segment;
            }
        }
        else {
            // Partial match (navigation) - resolution with revalidation logic
            const result = await Store.run(() => resolveAllSegmentsWithRevalidation(ctx.entries, ctx.routeKey, ctx.matched.params, ctx.handlerContext, ctx.clientSegmentSet, ctx.prevParams, ctx.request, ctx.prevUrl, ctx.url, ctx.loaderPromises, ctx.actionContext, ctx.interceptResult, ctx.localRouteName, ctx.pathname));
            // Update state with resolved segments
            state.segments = result.segments;
            state.matchedIds = result.matchedIds;
            // Yield all resolved segments
            for (const segment of result.segments) {
                yield segment;
            }
        }
        if (ms) {
            ms.metrics.push({ label: "pipeline:segment-resolve", duration: performance.now() - pipelineStart, startTime: pipelineStart - ms.requestStart });
        }
    };
}
//# sourceMappingURL=segment-resolution.js.map