import { toast } from "react-hot-toast";

function getCookie(name: string): string | null {
  let cookieValue = null;
  if (document.cookie && document.cookie !== "") {
    const cookies = document.cookie.split(";");
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      // Does this cookie string begin with the name we want?
      if (cookie.substring(0, name.length + 1) === name + "=") {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}

export const fetchWrapper = async (url: string, options: RequestInit = {}) => {
  const method = options.method?.toUpperCase();

  if (["POST", "PUT", "PATCH", "DELETE"].includes(method || "")) {
    const csrfToken = getCookie("csrftoken");
    if (csrfToken) {
      options.headers = {
        ...options.headers,
        "X-CSRFToken": csrfToken,
      };
    }
  }

  // Ensure credentials are included for all requests
  options.credentials = "include";

  const response = await fetch(url, options);

  if (response.status === 503) {
    toast.error("The service is temporarily unavailable. Please try again later.");
  }

  return response;
};
