const API_BASE = '/api';

export const getAuthToken = () => localStorage.getItem('auth_token');
export const setAuthToken = (token) => {
  if (token) {
    localStorage.setItem('auth_token', token);
  } else {
    localStorage.removeItem('auth_token');
  }
};

export const apiFetch = async (endpoint, options = {}) => {
  const token = getAuthToken();
  const headers = {
    'Content-Type': 'application/json',
    ...(token ? { 'Authorization': `Token ${token}` } : {}),
    ...options.headers,
  };

  const response = await fetch(`${API_BASE}${endpoint}`, {
    ...options,
    headers,
  });

  const contentType = response.headers.get('content-type');
  let data = null;

  if (contentType && contentType.includes('application/json')) {
    data = await response.json();
  }

  if (!response.ok) {
    let errorMsg = 'Ein Fehler ist aufgetreten.';
    if (data) {
      if (typeof data.error === 'string') errorMsg = data.error;
      else if (typeof data.detail === 'string') errorMsg = data.detail;
      else if (data.email) errorMsg = Array.isArray(data.email) ? data.email[0] : data.email;
      else if (data.username) errorMsg = Array.isArray(data.username) ? data.username[0] : data.username;
      else if (data.non_field_errors) errorMsg = data.non_field_errors[0];
    }
    throw new Error(errorMsg);
  }

  return data;
};
