import { mutation as gqlMutation, query as gqlQuery } from "gql-query-builder";
import { gql } from "@apollo/client/core";
import { useMutation, useQuery } from "@vue/apollo-composable";
import { classAttributes, isClassConstructor } from "../utils/object.js";
import { useApi } from "./api.js";
import { useRuntimeConfig } from "#imports";
export function useGraphQl() {
  function simplePromiseCall(operation, query2, variables, cache = false) {
    return new Promise((resolve, reject) => {
      useApi().postPromise(useRuntimeConfig().public.WS_GRAPHQL, {
        query: query2,
        variables
      }, void 0, void 0, cache).then((result) => {
        if (result.errors) reject(result.errors.map((error) => {
          return error.message;
        }).join("\n"));
        else {
          try {
            const dataObject = result.data;
            resolve(dataObject[operation]);
          } catch (error) {
            reject(error);
          }
        }
      }).catch((error) => {
        reject(error);
      });
    });
  }
  function query(operation, fields, variables, cache = false) {
    if (isClassConstructor(fields)) fields = classAttributes(fields);
    const builder = gqlQuery({ operation, fields, variables });
    const options = {
      fetchPolicy: cache ? "cache-first" : "no-cache"
    };
    return useQuery(gql(builder.query), builder.variables, options);
  }
  function queryPromise(operation, fields, variables, cache = false) {
    if (isClassConstructor(fields)) fields = classAttributes(fields);
    const builder = gqlQuery({ operation, fields, variables });
    return simplePromiseCall(operation, builder.query, builder.variables, cache);
  }
  function mutation(operation, fields, variables) {
    if (isClassConstructor(fields)) fields = classAttributes(fields);
    const builder = gqlMutation({ operation, fields, variables });
    return useMutation(gql(builder.query), { variables: builder.variables });
  }
  function mutationPromise(operation, fields, variables) {
    if (isClassConstructor(fields)) fields = classAttributes(fields);
    const builder = gqlMutation({ operation, fields, variables });
    return simplePromiseCall(operation, builder.query, builder.variables);
  }
  return { query, queryPromise, mutation, mutationPromise };
}
