import { useApi } from "./api.js";
import { buildApiEndpoint, stripModelByQualifier } from "./apiModel.js";
import { buildFields } from "./graphqlOperation.js";
import { useGraphqlBridge } from "../bridges/graphql.js";
export function useApiModelOperation(modelName) {
  const api = useApi();
  function prepFields(fields) {
    const { graphqlType } = useGraphqlBridge();
    const schema = graphqlType?.[modelName];
    if (!schema) return fields;
    return buildFields(schema, fields, 0);
  }
  return {
    read: (fields, variables, cache) => {
      const endpoint = buildApiEndpoint(modelName);
      return api.postPromise(
        endpoint,
        { variables, fields: prepFields(fields) },
        void 0,
        void 0,
        cache
      );
    },
    readPageable: (fields, variables, pageable) => {
      const endpoint = buildApiEndpoint(modelName, "pageable");
      return api.postPromise(endpoint, {
        ...variables || {},
        variables,
        fields: prepFields(fields),
        page: pageable?.page,
        perPage: pageable?.perPage,
        sortBy: pageable?.sortBy
      });
    },
    search: (fields, variables, search) => {
      const endpoint = buildApiEndpoint(modelName, "search");
      return api.postPromise(endpoint, {
        variables,
        fields: prepFields(fields),
        search
      });
    },
    create: (input, fields) => {
      const endpoint = buildApiEndpoint(stripModelByQualifier(modelName), "create");
      return api.postPromise(endpoint, { input, fields: prepFields(fields) });
    },
    update: (input, fields) => {
      const endpoint = buildApiEndpoint(stripModelByQualifier(modelName), "update");
      return api.postPromise(endpoint, { input, fields: prepFields(fields) });
    },
    delete: (input, fields) => {
      const endpoint = buildApiEndpoint(stripModelByQualifier(modelName), "delete");
      return api.postPromise(endpoint, { input, fields: prepFields(fields) });
    }
  };
}
