import axios from 'axios';

const BACKEND_URL = process.env.REACT_APP_BACKEND_URL;
const API = `${BACKEND_URL}/api`;

export const api = axios.create({
  baseURL: API,
});

// Add token to requests if exists
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('admin_token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Auth
export const adminLogin = (credentials) => api.post('/admin/login', credentials);

// Blog
export const getBlogPosts = (status = null) => {
  const params = status ? { status } : {};
  return api.get('/blog', { params });
};
export const getBlogPost = (id) => api.get(`/blog/${id}`);
export const createBlogPost = (data) => api.post('/blog', data);
export const updateBlogPost = (id, data) => api.put(`/blog/${id}`, data);
export const deleteBlogPost = (id) => api.delete(`/blog/${id}`);

// Services
export const getServices = () => api.get('/services');
export const createService = (data) => api.post('/services', data);
export const updateService = (id, data) => api.put(`/services/${id}`, data);
export const deleteService = (id) => api.delete(`/services/${id}`);

// Brands
export const getBrands = () => api.get('/brands');
export const createBrand = (data) => api.post('/brands', data);
export const updateBrand = (id, data) => api.put(`/brands/${id}`, data);
export const deleteBrand = (id) => api.delete(`/brands/${id}`);

// Areas
export const getAreas = () => api.get('/areas');
export const createArea = (data) => api.post('/areas', data);
export const updateArea = (id, data) => api.put(`/areas/${id}`, data);
export const deleteArea = (id) => api.delete(`/areas/${id}`);

// Contact
export const getContact = () => api.get('/contact');
export const updateContact = (data) => api.put('/contact', data);

// About
export const getAboutCards = () => api.get('/about');
export const createAboutCard = (data) => api.post('/about', data);
export const updateAboutCard = (id, data) => api.put(`/about/${id}`, data);
export const deleteAboutCard = (id) => api.delete(`/about/${id}`);

// Stats
export const getStats = () => api.get('/admin/stats');
export const getPublicStats = () => api.get('/stats/public');

// Products
export const getProducts = (category = null, featured = null) => {
  const params = {};
  if (category) params.category = category;
  if (featured !== null) params.featured = featured;
  return api.get('/products', { params });
};
export const getProduct = (id) => api.get(`/products/${id}`);
export const createProduct = (data) => api.post('/products', data);
export const updateProduct = (id, data) => api.put(`/products/${id}`, data);
export const deleteProduct = (id) => api.delete(`/products/${id}`);
