'use strict';

const queryKeyFactory = require('@lukemorales/query-key-factory');
const queryKeyDefs = require('../../packages/stack/src/plugins/form-builder/api/query-key-defs.cjs');

function isErrorResponse(response) {
  if (typeof response !== "object" || response === null) {
    return false;
  }
  const obj = response;
  return "error" in obj && obj.error !== null && obj.error !== void 0;
}
function toError(error) {
  if (error instanceof Error) {
    return error;
  }
  if (typeof error === "object" && error !== null) {
    const errorObj = error;
    const message = (typeof errorObj.message === "string" ? errorObj.message : null) || (typeof errorObj.error === "string" ? errorObj.error : null) || JSON.stringify(error);
    const err = new Error(message);
    Object.assign(err, error);
    return err;
  }
  return new Error(String(error));
}
function createFormBuilderQueryKeys(client, headers) {
  const forms = createFormsQueries(client, headers);
  const submissions = createSubmissionsQueries(client, headers);
  return queryKeyFactory.mergeQueryKeys(forms, submissions);
}
function createFormsQueries(client, headers) {
  return queryKeyFactory.createQueryKeys("forms", {
    list: (params = {}) => ({
      queryKey: ["list", queryKeyDefs.formsListDiscriminator(params)],
      queryFn: async () => {
        try {
          const response = await client("/forms", {
            method: "GET",
            query: {
              status: params.status,
              limit: params.limit ?? 20,
              offset: params.offset ?? 0
            },
            headers
          });
          if (isErrorResponse(response)) {
            throw toError(response.error);
          }
          return response.data;
        } catch (error) {
          throw error;
        }
      }
    }),
    bySlug: (slug) => ({
      queryKey: ["bySlug", slug],
      queryFn: async () => {
        if (!slug) return null;
        try {
          const response = await client("/forms/:slug", {
            method: "GET",
            params: { slug },
            headers
          });
          if (isErrorResponse(response)) {
            throw toError(response.error);
          }
          return response.data;
        } catch (error) {
          throw error;
        }
      }
    }),
    byId: (id) => ({
      queryKey: ["byId", id],
      queryFn: async () => {
        if (!id) return null;
        try {
          const response = await client("/forms/id/:id", {
            method: "GET",
            params: { id },
            headers
          });
          if (isErrorResponse(response)) {
            throw toError(response.error);
          }
          return response.data;
        } catch (error) {
          throw error;
        }
      }
    })
  });
}
function createSubmissionsQueries(client, headers) {
  return queryKeyFactory.createQueryKeys("formSubmissions", {
    list: (params) => ({
      queryKey: [queryKeyDefs.submissionsListDiscriminator(params)],
      queryFn: async () => {
        try {
          const response = await client("/forms/:formId/submissions", {
            method: "GET",
            params: { formId: params.formId },
            query: {
              limit: params.limit ?? 20,
              offset: params.offset ?? 0
            },
            headers
          });
          if (isErrorResponse(response)) {
            throw toError(response.error);
          }
          return response.data;
        } catch (error) {
          throw error;
        }
      }
    }),
    detail: (formId, subId) => ({
      queryKey: [formId, subId],
      queryFn: async () => {
        if (!formId || !subId) return null;
        try {
          const response = await client(
            "/forms/:formId/submissions/:subId",
            {
              method: "GET",
              params: { formId, subId },
              headers
            }
          );
          if (isErrorResponse(response)) {
            throw toError(response.error);
          }
          return response.data;
        } catch (error) {
          throw error;
        }
      }
    })
  });
}

exports.createFormBuilderQueryKeys = createFormBuilderQueryKeys;
