
const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:8080';

export const getToken = () => localStorage.getItem('token');

// Central fetch helper — automatically attaches the JWT token to every request
export const api = async (path, options = {}) => {
  const token = getToken();

  const response = await fetch(`${API_URL}${path}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...options.headers,
    },
  });

  if (!response.ok) {
    const text = await response.text();
    const error = text ? JSON.parse(text) : { error: 'Request failed' };
    throw new Error(error.error || 'Request failed');
  }

  // Handle empty responses (204 No Content, or 200 with no body)
  const text = await response.text();
  return text ? JSON.parse(text) : null;
};

/*import { mockPosts, mockUsers, mockCurrentUser } from './mockData';

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export const api = async (path, options = {}) => {
  await delay(400);

  const method = options.method || 'GET';

  // LOGIN
  if (path === '/api/auth/login') {
    return mockCurrentUser;
  }

  // REGISTER
  if (path === '/api/auth/register') {
    return mockCurrentUser;
  }

  // GET POSTS
  if (path === '/api/posts' && method === 'GET') {
    return mockPosts;
  }

  // CREATE POST
  if (path === '/api/posts' && method === 'POST') {
    const body = JSON.parse(options.body);

    const newPost = {
      id: Date.now(),
      user_id: 1,
      username: 'xava_dev',
      user_profil_bild: mockCurrentUser.profil_bild,

      bild: body.bild,
      title: body.title,
      description: body.description,
      ort: body.ort,

      likes: 0,
      liked_by: [],
      kommentar: [],
    };

    mockPosts.unshift(newPost);

    return newPost;
  }

  // USER PROFILE
  if (path === '/api/users/me') {
    return mockUsers[0];
  }

  // USER POSTS
  if (path.includes('/api/posts/user/')) {
    const userId = parseInt(path.split('/').pop());

    return mockPosts.filter((p) => p.user_id === userId);
  }

  // USER BY ID
  if (path.includes('/api/users/') && !path.includes('/following')) {
    const id = parseInt(path.split('/').pop());

    return mockUsers.find((u) => u.id === id);
  }

  // FOLLOWING
  if (path.includes('/following')) {
    return [mockUsers[1], mockUsers[2]];
  }

  // SEARCH USERS
  if (path.includes('/api/users/search')) {
    return mockUsers;
  }

  // LIKE POST
  if (path.includes('/like')) {
    const postId = parseInt(path.split('/')[3]);

    const post = mockPosts.find((p) => p.id === postId);

    if (!post) return null;

    const alreadyLiked = post.liked_by.includes(1);

    if (alreadyLiked) {
      post.liked_by = post.liked_by.filter((id) => id !== 1);
      post.likes--;
    } else {
      post.liked_by.push(1);
      post.likes++;
    }

    return post;
  }

  // COMMENTS
  if (path.includes('/comments') && method === 'POST') {
    const postId = parseInt(path.split('/')[3]);

    const post = mockPosts.find((p) => p.id === postId);

    const body = JSON.parse(options.body);

    const newComment = {
      comment_id: Date.now(),
      user_id: 1,
      username: 'xava_dev',
      text: body.text,
      likes: 0,
      liked_by: [],
    };

    post.kommentar.push(newComment);

    return newComment;
  }

  return null;
} */
