// Simple Fetch Wrapper
import { getTenantCode } from "./tenant";

export async function request(endpoint, options = {}) {
  const tenantCode = getTenantCode();
  if (!tenantCode) {
    throw new Error("Tenant code missing in URL");
  }
  const baseUrl = `/t/${tenantCode}/v1`;
  const token = localStorage.getItem("token");

  const headers = {
    "Content-Type": "application/json",
    ...options.headers,
  };

  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }

  if (options.body && !(options.body instanceof FormData)) {
    options.body = JSON.stringify(options.body);
  }

  if (options.body instanceof FormData) {
    delete headers["Content-Type"]; // Let browser set boundary
  }

  try {
    const res = await fetch(`${baseUrl}${endpoint}`, {
      ...options,
      headers,
    });

    const contentType = res.headers.get("content-type");
    let data;
    if (contentType && contentType.indexOf("application/json") !== -1) {
      data = await res.json();
    } else {
      data = await res.text();
    }

    if (!res.ok) {
      // Handle 401 Unauthorized
      if (res.status === 401) {
        localStorage.removeItem("token");
        localStorage.removeItem("user");
        const loginPath = `/t/${tenantCode}/auth/login`;
        // Redirect to login if not already there
        if (!window.location.pathname.includes("/auth/login")) {
          window.location.href = loginPath;
        }
      }

      // Handle errorx response { code, message, error_id }
      const errorMsg =
        data.message || `Request failed with status ${res.status}`;
      throw new Error(errorMsg);
    }

    return data;
  } catch (err) {
    console.error("API Request Error:", err);
    throw err;
  }
}
