import { clearAuthHeader, getAuthHeader } from "../auth/authStore";

export async function apiFetch<T>(input: string, init?: RequestInit): Promise<T> {
  const base = import.meta.env.VITE_API_BASE ?? "/api";
  const authHeader = getAuthHeader();
  if (!authHeader) {
    throw new Error("Kimlik bilgileri gerekli");
  }

  const response = await fetch(`${base}${input}`, {
    ...init,
    headers: {
      "Content-Type": "application/json",
      Authorization: authHeader,
      ...(init?.headers ?? {})
    }
  });

  if (response.status === 401) {
    clearAuthHeader();
    window.location.href = "/login";
  }

  if (!response.ok) {
    const text = await response.text();
    throw new Error(text || "API hatasi");
  }

  if (response.status === 204) {
    return undefined as T;
  }

  return (await response.json()) as T;
}
