import { jsx } from "react/jsx-runtime";
import { useEffect, useRef } from "react";
import { useForm } from "@tachybase/schema";
import { useAPIClient, useRequest } from "../../../../api-client/index.mjs";
import { AsyncDataProvider } from "../../../../async-data-provider/index.mjs";
import { useRecord } from "../../../../record-provider/index.mjs";
const SQLRequestProvider = (props)=>{
    const api = useAPIClient();
    const form = useForm();
    const record = useRecord();
    let { manual } = props;
    manual = void 0 === manual ? true : manual;
    const result = useRequest((sql)=>api.resource('sqlCollection').execute({
            values: {
                sql
            }
        }).then((res)=>{
            var _res_data;
            return (null == res ? void 0 : null == (_res_data = res.data) ? void 0 : _res_data.data) || {
                data: [],
                fields: [],
                sources: []
            };
        }), {
        manual: true,
        onSuccess: (data)=>{
            const { sources } = data;
            const formSources = form.values.sources || [];
            form.setValuesIn('sources', Array.from(new Set([
                ...formSources,
                ...sources
            ])));
        }
    });
    const { run } = result;
    const sql = form.values.sql || record.sql;
    const first = useRef(true);
    useEffect(()=>{
        if (sql && first.current) run(sql);
        first.current = false;
    }, [
        manual,
        run,
        sql
    ]);
    return /*#__PURE__*/ jsx(AsyncDataProvider, {
        value: result,
        children: props.children
    });
};
export { SQLRequestProvider };
