import axios from 'axios';

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

// Create axios instance
const apiClient = axios.create({
  baseURL: API,
  headers: {
    'Content-Type': 'application/json',
  },
});

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

// Auth API
export const authAPI = {
  login: async (email, password) => {
    const response = await apiClient.post('/auth/login', { email, password });
    return response.data;
  },
  verify: async () => {
    const response = await apiClient.post('/auth/verify');
    return response.data;
  },
};

// Destinations API
export const destinationsAPI = {
  getAll: async (category, search) => {
    const params = {};
    if (category) params.category = category;
    if (search) params.search = search;
    const response = await apiClient.get('/destinations', { params });
    return response.data;
  },
  getById: async (id) => {
    const response = await apiClient.get(`/destinations/${id}`);
    return response.data;
  },
  create: async (destination) => {
    const response = await apiClient.post('/destinations', destination);
    return response.data;
  },
  update: async (id, destination) => {
    const response = await apiClient.put(`/destinations/${id}`, destination);
    return response.data;
  },
  delete: async (id) => {
    const response = await apiClient.delete(`/destinations/${id}`);
    return response.data;
  },
};

// Specials API
export const specialsAPI = {
  getAll: async () => {
    const response = await apiClient.get('/specials');
    return response.data;
  },
  create: async (special) => {
    const response = await apiClient.post('/specials', special);
    return response.data;
  },
  update: async (id, special) => {
    const response = await apiClient.put(`/specials/${id}`, special);
    return response.data;
  },
  deleteByDestination: async (destinationId) => {
    const response = await apiClient.delete(`/specials/destination/${destinationId}`);
    return response.data;
  },
};

// Contact API
export const contactAPI = {
  submit: async (contact) => {
    const response = await apiClient.post('/contact', contact);
    return response.data;
  },
};

// Newsletter API
export const newsletterAPI = {
  subscribe: async (email) => {
    const response = await apiClient.post('/newsletter/subscribe', { email });
    return response.data;
  },
};

// Image Upload API
export const uploadAPI = {
  uploadImage: async (file) => {
    const formData = new FormData();
    formData.append('file', file);
    const response = await apiClient.post('/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    return response.data;
  },
};

export default apiClient;
