import { jsx } from "react/jsx-runtime";
import { createContext, useContext, useMemo } from "react";
import { useDeepCompareEffect, useUpdateEffect } from "ahooks";
import { useAPIClient, useRequest } from "../../api-client/index.mjs";
import { useDataLoadingMode } from "../../modules/blocks/data-blocks/details-multi/setDataLoadingModeSettingsItem.mjs";
import { useSourceKey } from "../../modules/blocks/useSourceKey.mjs";
import { CollectionRecord, CollectionRecordProvider } from "../collection-record/index.mjs";
import { useDataSourceHeaders } from "../utils.mjs";
import { useDataBlockProps } from "./DataBlockProvider.mjs";
import { useDataBlockResource } from "./DataBlockResourceProvider.mjs";
const BlockRequestContext = /*#__PURE__*/ createContext(null);
BlockRequestContext.displayName = 'BlockRequestContext';
function useCurrentRequest(options) {
    const dataLoadingMode = useDataLoadingMode();
    const resource = useDataBlockResource();
    const { action, params = {}, record, requestService, requestOptions } = options;
    if (void 0 === params.filterByTk) delete params.filterByTk;
    const request = useRequest(requestService ? requestService : (customParams)=>{
        if (record) return Promise.resolve({
            data: record
        });
        if (!action) throw new Error("[tachybase]: The 'action' parameter is missing in the 'DataBlockRequestProvider' component");
        return resource[action]({
            ...params,
            ...customParams
        }).then((res)=>res.data);
    }, {
        ...requestOptions,
        manual: true
    });
    useDeepCompareEffect(()=>{
        if (action && 'auto' === dataLoadingMode) request.run();
    }, [
        params,
        action,
        record
    ]);
    useUpdateEffect(()=>{
        if (action && 'auto' === dataLoadingMode) request.run();
    }, [
        resource
    ]);
    return request;
}
function useParentRequest(options) {
    const { sourceId, association, parentRecord } = options;
    const api = useAPIClient();
    const dataBlockProps = useDataBlockProps();
    const headers = useDataSourceHeaders(dataBlockProps.dataSource);
    const sourceKey = useSourceKey(association);
    return useRequest(async ()=>{
        if (parentRecord) return Promise.resolve({
            data: parentRecord
        });
        if (!association || !sourceKey) return Promise.resolve({
            data: void 0
        });
        const arr = association.split('.');
        const url = "".concat(arr[0], ":get?filter[").concat(sourceKey, "]=").concat(sourceId);
        const res = await api.request({
            url,
            headers
        });
        return res.data;
    }, {
        refreshDeps: [
            association,
            parentRecord,
            sourceId
        ]
    });
}
const BlockRequestProvider = (param)=>{
    let { children } = param;
    var _parentRequest_data, _currentRequest_data;
    const props = useDataBlockProps();
    const { action, filterByTk, sourceId, params = {}, association, collection, record, parentRecord, requestOptions, requestService } = props;
    const currentRequest = useCurrentRequest({
        action,
        sourceId,
        record,
        association,
        collection,
        requestOptions,
        requestService,
        params: {
            ...params,
            filterByTk: filterByTk || params.filterByTk
        }
    });
    const parentRequest = useParentRequest({
        sourceId,
        association,
        parentRecord
    });
    const memoizedParentRecord = useMemo(()=>{
        var _parentRequest_data, _parentRequest_data1;
        return (null == (_parentRequest_data = parentRequest.data) ? void 0 : _parentRequest_data.data) && new CollectionRecord({
            isNew: false,
            data: null == (_parentRequest_data1 = parentRequest.data) ? void 0 : _parentRequest_data1.data
        });
    }, [
        null == (_parentRequest_data = parentRequest.data) ? void 0 : _parentRequest_data.data
    ]);
    return /*#__PURE__*/ jsx(BlockRequestContext.Provider, {
        value: currentRequest,
        children: 'list' !== action ? /*#__PURE__*/ jsx(CollectionRecordProvider, {
            isNew: null == action,
            record: null == (_currentRequest_data = currentRequest.data) ? void 0 : _currentRequest_data.data,
            parentRecord: memoizedParentRecord,
            children: children
        }) : /*#__PURE__*/ jsx(CollectionRecordProvider, {
            isNew: false,
            record: null,
            parentRecord: memoizedParentRecord,
            children: children
        })
    });
};
const useDataBlockRequest = ()=>{
    const context = useContext(BlockRequestContext);
    return context;
};
export { BlockRequestContext, BlockRequestProvider, useDataBlockRequest };
