const API_BASE = (import.meta as any).env.VITE_API_BASE || '/api';

function getJwt() {
  try {
    const stored = localStorage.getItem('spotify-user');
    if (!stored) return null;
    const parsed = JSON.parse(stored);
    return parsed?.jwt || parsed?.token || null;
  } catch {
    return null;
  }
}

export async function apiPost<T>(path: string, body?: any, token?: string): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : getJwt() ? { Authorization: `Bearer ${getJwt()}` } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(text || `Request failed: ${res.status}`);
  }
  return res.json();
}

export async function apiGet<T>(path: string, token?: string): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    headers: {
      ...(token ? { Authorization: `Bearer ${token}` } : getJwt() ? { Authorization: `Bearer ${getJwt()}` } : {}),
    },
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(text || `Request failed: ${res.status}`);
  }
  return res.json();
}

export async function apiPostForm<T>(path: string, form: Record<string, string>, token?: string): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      ...(token ? { Authorization: `Bearer ${token}` } : getJwt() ? { Authorization: `Bearer ${getJwt()}` } : {}),
    },
    body: new URLSearchParams(form).toString(),
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(text || `Request failed: ${res.status}`);
  }
  return res.json();
}


