import { ensureArray } from '@takeshape/util';
import { getQuery } from "../refs.js";
import { getIdField } from "../schema-util.js";
import { getResolverServices } from "../services/util.js";
import { isCachedShape, isServiceResolver } from "../types/index.js";
export function serviceHasIndexedShapes(schema, serviceId) {
    for (const shape of Object.values(schema.shapes ?? {})) {
        const indexingEnabled = isCachedShape(shape);
        const listConfigs = shape.loaders?.list;
        if (indexingEnabled && listConfigs) {
            for (const { query: queryRef } of ensureArray(listConfigs)) {
                const resolved = getQuery(schema, queryRef);
                if (resolved && isServiceResolver(resolved.query.resolver) && resolved.query.resolver.service === serviceId) {
                    return true;
                }
            }
        }
    }
    return false;
}
export function getIndexedServices(projectSchema, configs) {
    return ensureArray(configs).reduce((services, queryConfig) => {
        const resolved = queryConfig?.query ? getQuery(projectSchema, queryConfig.query) : undefined;
        return resolved?.query ? [...services, ...getResolverServices(resolved.query.resolver)] : services;
    }, []);
}
function flattenListQueryConfigs(base, queryConfig, maybeConfigArray) {
    return (maybeConfigArray &&
        ensureArray(maybeConfigArray).flatMap((config) => ensureArray(config.args).map((args) => ({
            ...base,
            ...queryConfig,
            ...config,
            args
        }))));
}
function getQueryIndexConfigHelper(op) {
    return ({ shapes }, shapeName) => {
        const { cache, loaders } = shapes[shapeName] ?? {};
        if (cache && loaders) {
            const idField = getIdField(cache);
            if (op === 'list') {
                return flattenListQueryConfigs({ shapeName, idField }, cache.fragment, loaders.list);
            }
            const queryConfig = loaders.get;
            if (queryConfig) {
                return {
                    idField,
                    shapeName,
                    ...cache.fragment,
                    ...queryConfig
                };
            }
        }
    };
}
export const getListQueryIndexConfigs = getQueryIndexConfigHelper('list');
export const getGetQueryIndexConfig = getQueryIndexConfigHelper('get');
