const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:8000/api';

export function getSessionKey(): string {
  if (typeof window === 'undefined') return '';
  let key = localStorage.getItem('ev_session_key');
  if (!key) {
    key = 'sess_' + Math.random().toString(36).substring(2) + Date.now().toString(36);
    localStorage.setItem('ev_session_key', key);
  }
  return key;
}

export function getAuthHeaders(): HeadersInit {
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
  };
  if (typeof window !== 'undefined') {
    const token = localStorage.getItem('access_token');
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    headers['X-Session-Key'] = getSessionKey();
  }
  return headers;
}

export async function fetchCatalog(search?: string, voltage?: string, chemistry?: string) {
  const params = new URLSearchParams();
  if (search) params.append('search', search);
  if (voltage) params.append('voltage', voltage);
  if (chemistry) params.append('chemistry', chemistry);

  const res = await fetch(`${API_BASE}/catalog/products/?${params.toString()}`, {
    cache: 'no-store'
  });
  if (!res.ok) throw new Error('Failed to fetch catalog');
  return res.json();
}

export async function fetchProduct(slug: string) {
  const res = await fetch(`${API_BASE}/catalog/products/${slug}/`, {
    cache: 'no-store'
  });
  if (!res.ok) throw new Error('Product not found');
  return res.json();
}

export async function checkCompatibility(vehicleModelId: number) {
  const res = await fetch(`${API_BASE}/vehicles/compatibility/?vehicle_model_id=${vehicleModelId}`);
  if (!res.ok) throw new Error('Failed to fetch compatibility list');
  return res.json();
}

export async function getCart() {
  const res = await fetch(`${API_BASE}/cart/`, {
    headers: getAuthHeaders(),
  });
  return res.json();
}

export async function addToCart(productId: number, quantity = 1) {
  const res = await fetch(`${API_BASE}/cart/items/`, {
    method: 'POST',
    headers: getAuthHeaders(),
    body: JSON.stringify({ product_id: productId, quantity }),
  });
  return res.json();
}

export async function updateCartItem(itemId: number, quantity: number) {
  const res = await fetch(`${API_BASE}/cart/items/${itemId}/`, {
    method: 'PATCH',
    headers: getAuthHeaders(),
    body: JSON.stringify({ quantity }),
  });
  return res.json();
}

export async function removeCartItem(itemId: number) {
  const res = await fetch(`${API_BASE}/cart/items/${itemId}/`, {
    method: 'DELETE',
    headers: getAuthHeaders(),
  });
  return res.json();
}
