"use client";
import { useState, useRef, useCallback } from "react";
function useApiRequest() {
  const [status, setStatus] = useState("idle");
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);
  const abortControllerRef = useRef(null);
  const execute = useCallback(async (config) => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }
    abortControllerRef.current = new AbortController();
    setStatus("loading");
    setResponse(null);
    setError(null);
    const startTime = performance.now();
    try {
      const headers = {
        ...config.headers,
        "Content-Type": "application/json"
      };
      if (config.authType === "apiKey" && config.apiKey) {
        headers["x-api-key"] = config.apiKey;
      }
      const fetchOptions = {
        method: config.method,
        headers,
        signal: abortControllerRef.current.signal,
        credentials: config.authType === "session" ? "include" : "omit"
      };
      if (["POST", "PATCH", "PUT"].includes(config.method) && config.body) {
        fetchOptions.body = config.body;
      }
      const res = await fetch(config.url, fetchOptions);
      const endTime = performance.now();
      const timing = Math.round(endTime - startTime);
      const responseHeaders = {};
      res.headers.forEach((value, key) => {
        responseHeaders[key] = value;
      });
      let body;
      const contentType = res.headers.get("content-type");
      if (contentType == null ? void 0 : contentType.includes("application/json")) {
        body = await res.json();
      } else {
        body = await res.text();
      }
      const apiResponse = {
        status: res.status,
        statusText: res.statusText,
        headers: responseHeaders,
        body,
        timing
      };
      setResponse(apiResponse);
      setStatus("success");
    } catch (err) {
      if (err instanceof Error) {
        if (err.name === "AbortError") {
          setStatus("cancelled");
          setError("Request cancelled");
        } else {
          setStatus("error");
          setError(err.message);
        }
      } else {
        setStatus("error");
        setError("Unknown error occurred");
      }
    }
  }, []);
  const cancel = useCallback(() => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }
  }, []);
  const reset = useCallback(() => {
    setStatus("idle");
    setResponse(null);
    setError(null);
  }, []);
  return {
    status,
    response,
    error,
    execute,
    cancel,
    reset
  };
}
export {
  useApiRequest
};
