const BASE_URL = import.meta.env.VITE_API_URL || "http://localhost:8008";

// Helper pour gérer les erreurs
const handleResponse = async (response) => {
  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: "Erreur réseau" }));
    throw new Error(error.detail || `Erreur ${response.status}`);
  }
  return response.json();
};

// Products
export const fetchProducts = async () => {
  const response = await fetch(`${BASE_URL}/products`);
  return handleResponse(response);
};

export const fetchProduct = async (id) => {
  const response = await fetch(`${BASE_URL}/products/${id}`);
  return handleResponse(response);
};

export const createProduct = async (data) => {
  const response = await fetch(`${BASE_URL}/products`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  });
  return handleResponse(response);
};

export const updateProduct = async (id, data) => {
  const response = await fetch(`${BASE_URL}/products/${id}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  });
  return handleResponse(response);
};

export const deleteProduct = async (id) => {
  const response = await fetch(`${BASE_URL}/products/${id}`, {
    method: "DELETE",
  });
  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: "Erreur réseau" }));
    throw new Error(error.detail || `Erreur ${response.status}`);
  }
  return true;
};

// Scraping
export const scrapeProduct = async (id) => {
  const response = await fetch(`${BASE_URL}/scrape/product/${id}`, {
    method: "POST",
  });
  return handleResponse(response);
};

export const scrapeAll = async () => {
  const response = await fetch(`${BASE_URL}/scrape/all`, {
    method: "POST",
  });
  return handleResponse(response);
};

// Preview scrape (scrape sans enregistrer pour prévisualisation)
export const scrapePreview = async (url) => {
  const response = await fetch(`${BASE_URL}/scrape/preview`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ url }),
  });
  return handleResponse(response);
};

// Snapshots
export const fetchSnapshots = async (productId, days = 30) => {
  const response = await fetch(`${BASE_URL}/products/${productId}/snapshots?days=${days}`);
  return handleResponse(response);
};

// Debug
export const fetchDebugTables = async (limit = 50) => {
  const response = await fetch(`${BASE_URL}/debug/tables?limit=${limit}`);
  return handleResponse(response);
};

export const fetchDebugLogs = async (lines = 100) => {
  const response = await fetch(`${BASE_URL}/debug/logs?lines=${lines}`);
  return handleResponse(response);
};

// Config frontend (via API backend)
export const fetchFrontendConfig = async () => {
  const response = await fetch(`${BASE_URL}/config/frontend`);
  return handleResponse(response);
};

export const updateFrontendConfig = async (config) => {
  const response = await fetch(`${BASE_URL}/config/frontend`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(config),
  });
  return handleResponse(response);
};

// Config backend
export const fetchBackendConfig = async () => {
  const response = await fetch(`${BASE_URL}/config/backend`);
  return handleResponse(response);
};

export const updateBackendConfig = async (config) => {
  const response = await fetch(`${BASE_URL}/config/backend`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(config),
  });
  return handleResponse(response);
};

// Version backend
export const fetchBackendVersion = async () => {
  const response = await fetch(`${BASE_URL}/version`);
  return handleResponse(response);
};

// System stats
export const fetchSystemStats = async () => {
  const response = await fetch(`${BASE_URL}/stats`);
  return handleResponse(response);
};

// Database backup
export const fetchDatabaseInfo = async () => {
  const response = await fetch(`${BASE_URL}/config/database/info`);
  return handleResponse(response);
};

export const downloadDatabaseBackup = () => {
  // Téléchargement direct via le navigateur
  window.location.href = `${BASE_URL}/config/database/backup`;
};

export const restoreDatabase = async (file) => {
  const formData = new FormData();
  formData.append("file", file);

  const response = await fetch(`${BASE_URL}/config/database/restore`, {
    method: "POST",
    body: formData,
  });
  return handleResponse(response);
};
