export const API_URL = "https://examjam-api.pptx704.com";

// Cookie utility functions
const setCookie = (name, value, days = 7) => {
  if (typeof document === "undefined") return;

  if (value === null) {
    // Delete cookie by setting expiration to past date
    document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Strict; Secure`;
  } else {
    const expires = new Date();
    expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/; SameSite=Strict; Secure`;
  }
};

export const login = async (form, setToken) => {
  const response = await fetch(`${API_URL}/auth/login`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(form),
  });

  const data = await response.json();

  if (!response.ok) {
    throw new Error(data.message || "Login failed");
  }

  // Save the token to cookies instead of secure storage
  setCookie("authToken", data.token);
  setToken(data.token); // Update the token in context
};

const handleError = (error) => {
  // Check if error has a "detail" property
  if (error?.detail) {
    // Match the field causing the issue
    const match = error.detail.match(/Key \((.*?)\)=\((.*?)\)/);

    if (match) {
      const field = match[1]; // The field name, e.g., "phone"
      const value = match[2]; // The duplicate value, e.g., "0987654321"
      return `The ${field} already exists. Please use a different value.`;
    }
  }
  return "An unexpected error occurred. Please try again.";
};

export const register = async (form, setToken) => {
  const response = await fetch(`${API_URL}/auth/register`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(form),
  });

  const data = await response.json(); // Parse the response JSON

  if (!response.ok) {
    // Instead of throwing a string, include full error data for debugging
    const error = new Error(data?.detail || "Registration failed");
    error.response = data; // Attach the full response for later use
    throw error;
  }

  // Save the token to cookies instead of secure storage
  setCookie("authToken", data.token);
  setToken(data.token); // Update the token in context
};

// Additional utility function to get token from cookies (if needed elsewhere)
export const getTokenFromCookie = () => {
  if (typeof document === "undefined") return null;

  const value = `; ${document.cookie}`;
  const parts = value.split(`; authToken=`);
  if (parts.length === 2) {
    return parts.pop()?.split(";").shift() || null;
  }
  return null;
};

// Utility function to clear auth token (for logout)
export const clearAuthToken = () => {
  setCookie("authToken", null);
};
