import { jsx } from "react/jsx-runtime";
import { createContext, useContext, useMemo } from "react";
import { useAPIClient } from "../../api-client/index.mjs";
import { useCollectionManager } from "../collection/index.mjs";
import { CollectionRecord } from "../collection-record/index.mjs";
import { useDataSourceHeaders } from "../utils.mjs";
import { useDataBlockProps } from "./DataBlockProvider.mjs";
const DataBlockResourceContext = /*#__PURE__*/ createContext(null);
DataBlockResourceContext.displayName = 'DataBlockResourceContext';
const DataBlockResourceProvider = (param)=>{
    let { children } = param;
    const dataBlockProps = useDataBlockProps();
    const cm = useCollectionManager();
    const { association, collection, dataSource, sourceId, parentRecord } = dataBlockProps;
    const api = useAPIClient();
    const headers = useDataSourceHeaders(dataSource);
    const collectionName = useMemo(()=>'string' == typeof collection ? collection : null == collection ? void 0 : collection.name, [
        collection
    ]);
    const sourceIdValue = useMemo(()=>{
        if (sourceId) return sourceId;
        if (association && parentRecord) {
            const sourceKey = cm.getSourceKeyByAssocation(association);
            const parentRecordData = parentRecord instanceof CollectionRecord ? parentRecord.data : parentRecord;
            return parentRecordData[sourceKey];
        }
    }, [
        association,
        sourceId,
        parentRecord
    ]);
    const resource = useMemo(()=>{
        if (association) return api.resource(association, sourceIdValue, headers);
        var _dataBlockProps_resource_deprecated;
        return api.resource(null != (_dataBlockProps_resource_deprecated = dataBlockProps.resource_deprecated) ? _dataBlockProps_resource_deprecated : collectionName, void 0, headers);
    }, [
        api,
        association,
        collection,
        sourceIdValue,
        headers,
        dataBlockProps.resource_deprecated
    ]);
    return /*#__PURE__*/ jsx(DataBlockResourceContext.Provider, {
        value: resource,
        children: children
    });
};
function useDataBlockResource() {
    const context = useContext(DataBlockResourceContext);
    if (!context) throw new Error('useDataBlockResource() must be used within a DataBlockResourceProvider');
    return context;
}
export { DataBlockResourceContext, DataBlockResourceProvider, useDataBlockResource };
