'use strict';

var react = require('react');

// src/gateway/use-athena-gateway.ts

// src/gateway/client.ts
var DEFAULT_BASE_URL = "https://athena-db.com";
var DEFAULT_CLIENT = "railway_direct";
function parseResponseText(text) {
  if (!text) return null;
  try {
    return JSON.parse(text);
  } catch {
    return text;
  }
}
function normalizeHeaderValue(value) {
  return value ? value : void 0;
}
function buildHeaders(config, options) {
  const mergedStripNulls = options?.stripNulls ?? config.stripNulls ?? true;
  const finalClient = options?.client ?? config.client ?? DEFAULT_CLIENT;
  const finalApiKey = options?.apiKey ?? config.apiKey;
  const finalSupabaseUrl = options?.supabaseUrl ?? config.supabaseUrl;
  const finalSupabaseKey = options?.supabaseKey ?? config.supabaseKey;
  const finalPublishEvent = options?.publishEvent ?? config.publishEvent;
  const extraHeaders = {
    ...config.headers ?? {},
    ...options?.headers ?? {}
  };
  const headers = {
    "Content-Type": "application/json"
  };
  if (options?.userId ?? config.userId) {
    headers["X-User-Id"] = options?.userId ?? config.userId ?? "";
  }
  if (options?.companyId ?? config.companyId) {
    headers["X-Company-Id"] = options?.companyId ?? config.companyId ?? "";
  }
  if (options?.organizationId ?? config.organizationId) {
    headers["X-Organization-Id"] = options?.organizationId ?? config.organizationId ?? "";
  }
  if (finalClient) {
    headers["X-Athena-Client"] = finalClient;
  }
  if (typeof mergedStripNulls === "boolean") {
    headers["X-Strip-Nulls"] = mergedStripNulls ? "true" : "false";
  }
  if (finalPublishEvent) {
    headers["X-Publish-Event"] = finalPublishEvent;
  }
  if (finalApiKey) {
    headers["apikey"] = finalApiKey;
    headers["x-api-key"] = headers["x-api-key"] ?? finalApiKey;
  }
  if (finalSupabaseUrl) {
    headers["x-supabase-url"] = finalSupabaseUrl;
  }
  if (finalSupabaseKey) {
    headers["x-supabase-key"] = finalSupabaseKey;
  }
  Object.entries(extraHeaders).forEach(([key, value]) => {
    const normalized = normalizeHeaderValue(value);
    if (normalized) {
      headers[key] = normalized;
    }
  });
  return headers;
}
async function callAthena(config, endpoint, method, payload, options) {
  const baseUrl = (options?.baseUrl ?? config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
  const url = `${baseUrl}${endpoint}`;
  const headers = buildHeaders(config, options);
  try {
    const response = await fetch(url, {
      method,
      headers,
      body: JSON.stringify(payload)
    });
    const rawText = await response.text();
    const parsed = parseResponseText(rawText ?? "");
    const parsedPayload = parsed;
    const parsedError = parsedPayload && typeof parsedPayload === "object" ? parsedPayload.error ?? parsedPayload.message : void 0;
    const hasError = typeof parsedError === "string" && parsedError.length > 0 ? parsedError : void 0;
    return {
      ok: response.ok,
      status: response.status,
      data: parsed ?? null,
      error: hasError,
      raw: parsed
    };
  } catch (callError) {
    const message = callError instanceof Error ? callError.message : String(callError);
    return {
      ok: false,
      status: 0,
      data: null,
      error: message,
      raw: null
    };
  }
}
function createAthenaGatewayClient(config = {}) {
  return {
    baseUrl: (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, ""),
    buildHeaders(options) {
      return buildHeaders(config, options);
    },
    fetchGateway(payload, options) {
      return callAthena(config, "/gateway/fetch", "POST", payload, options);
    },
    insertGateway(payload, options) {
      return callAthena(config, "/gateway/insert", "PUT", payload, options);
    },
    updateGateway(payload, options) {
      return callAthena(config, "/gateway/update", "POST", payload, options);
    },
    deleteGateway(payload, options) {
      return callAthena(config, "/gateway/delete", "DELETE", payload, options);
    }
  };
}

// src/gateway/use-athena-gateway.ts
function useAthenaGateway(config) {
  const [isLoading, setIsLoading] = react.useState(false);
  const [error, setError] = react.useState(null);
  const [lastRequest, setLastRequest] = react.useState(
    null
  );
  const [lastResponse, setLastResponse] = react.useState(null);
  const client = react.useMemo(
    () => createAthenaGatewayClient({
      client: config?.client,
      baseUrl: config?.baseUrl,
      apiKey: config?.apiKey,
      supabaseUrl: config?.supabaseUrl,
      supabaseKey: config?.supabaseKey,
      publishEvent: config?.publishEvent,
      stripNulls: config?.stripNulls,
      headers: config?.headers,
      userId: config?.userId,
      companyId: config?.companyId,
      organizationId: config?.organizationId
    }),
    [
      config?.baseUrl,
      config?.client,
      config?.apiKey,
      config?.supabaseUrl,
      config?.supabaseKey,
      config?.publishEvent,
      config?.stripNulls,
      config?.headers,
      config?.userId,
      config?.companyId,
      config?.organizationId
    ]
  );
  const callWithLifecycle = react.useCallback(
    async (fn, metadata) => {
      const requestLog = {
        endpoint: metadata.endpoint,
        method: metadata.method,
        payload: metadata.payload,
        headers: client.buildHeaders(metadata.options),
        timestamp: (/* @__PURE__ */ new Date()).toISOString()
      };
      setLastRequest(requestLog);
      setIsLoading(true);
      setError(null);
      let response;
      try {
        response = await fn();
        setLastResponse({ ...response, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
        if (!response.ok) {
          const message = response.error || `Athena gateway ${metadata.method} ${metadata.endpoint} failed`;
          setError(message);
          throw new Error(message);
        }
        return response;
      } catch (callError) {
        const message = callError instanceof Error ? callError.message : String(callError);
        setError(message);
        setLastResponse({
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          status: response?.status ?? 0,
          ok: false,
          data: null,
          raw: null,
          error: message
        });
        throw callError;
      } finally {
        setIsLoading(false);
      }
    },
    [client]
  );
  const normalizedConfigStripNulls = react.useMemo(
    () => config?.stripNulls ?? true,
    [config?.stripNulls]
  );
  const fetchGateway = react.useCallback(
    (payload, options) => {
      const normalizedPayload = {
        ...payload,
        conditions: payload.conditions ?? [],
        strip_nulls: payload.strip_nulls ?? options?.stripNulls ?? normalizedConfigStripNulls
      };
      return callWithLifecycle(
        () => client.fetchGateway(normalizedPayload, options),
        {
          endpoint: "/gateway/fetch",
          method: "POST",
          payload: normalizedPayload,
          options
        }
      );
    },
    [callWithLifecycle, client, normalizedConfigStripNulls]
  );
  const insertGateway = react.useCallback(
    (payload, options) => callWithLifecycle(() => client.insertGateway(payload, options), {
      endpoint: "/gateway/insert",
      method: "PUT",
      payload,
      options
    }),
    [callWithLifecycle, client]
  );
  const updateGateway = react.useCallback(
    (payload, options) => {
      const normalizedPayload = {
        ...payload,
        conditions: payload.conditions ?? [],
        strip_nulls: payload.strip_nulls ?? options?.stripNulls ?? normalizedConfigStripNulls
      };
      return callWithLifecycle(
        () => client.updateGateway(normalizedPayload, options),
        {
          endpoint: "/gateway/update",
          method: "POST",
          payload: normalizedPayload,
          options
        }
      );
    },
    [callWithLifecycle, client, normalizedConfigStripNulls]
  );
  const deleteGateway = react.useCallback(
    (payload, options) => {
      if (!payload.resource_id) {
        throw new Error(
          "deleteGateway requires resource_id (the unique identifier of the record to delete)"
        );
      }
      return callWithLifecycle(
        () => client.deleteGateway(payload, options),
        { endpoint: "/gateway/delete", method: "DELETE", payload, options }
      );
    },
    [callWithLifecycle, client]
  );
  return {
    fetchGateway,
    insertGateway,
    updateGateway,
    deleteGateway,
    isLoading,
    error,
    lastRequest,
    lastResponse,
    baseUrl: client.baseUrl
  };
}

exports.useAthenaGateway = useAthenaGateway;
//# sourceMappingURL=react.js.map
//# sourceMappingURL=react.js.map