const API_URL = import.meta.env.VITE_EFC_API_URL || 'http://localhost:8000';
import { fetchWithAuth, postWithAuth, putWithAuth, deleteWithAuth } from '../fetchWithAuth';

// Función helper para manejar respuestas

async function handleResponse(response, operation = 'operación') {
  if (response.status === 401) {
    throw new Error('SESSION_EXPIRED');
  }
  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Error ${response.status}: ${response.statusText}`);
  }
  const contentType = response.headers.get('content-type');
  if (!contentType || !contentType.includes('application/json')) {
    throw new Error('El servidor no devolvió JSON válido');
  }
  return response.json();
}

export async function fetchUsers() {
  const url = `${API_URL}/user/users/`;
  const res = await fetchWithAuth(url);
  return handleResponse(res, 'Fetch Users');
}

export async function createUser(userData) {
  const url = `${API_URL}/user/users/`;
  const res = await postWithAuth(url, userData);
  return handleResponse(res, 'Create User');
}

export async function updateUser(id, userData) {
  const url = `${API_URL}/user/users/${id}/`;
  const res = await putWithAuth(url, userData);
  return handleResponse(res, 'Update User');
}

export async function deleteUser(id) {
  const url = `${API_URL}/user/users/${id}/`;
  const res = await deleteWithAuth(url);
  if (!res.ok) throw new Error(`Error ${res.status}: ${res.statusText}`);
  return true;
}

export async function getCurrentUser(token) {
  const url = `${API_URL}/user/users/me/`;
  const res = await fetch(url, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
  });
  return handleResponse(res, 'Get Current User');
}
